【问题标题】:why won't this code cause infinite loop?为什么这段代码不会导致无限循环?
【发布时间】:2012-07-11 09:20:02
【问题描述】:

Xcode 模板代码:MasterDetailApplication(使用核心数据) 在 MasterViewController.m 中,实现

- (NSFetchedResultsController *)fetchedResultsController
{
  if (__fetchedResultsController != nil) {
    return __fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];

// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController  = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
     // Replace this implementation with code to handle the error appropriately.
     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return __fetchedResultsController;
}    

问题是:这段代码在 getter 中使用了属性,为什么这不会导致无限循环? 我的意思是这一行:

self.fetchedResultsController  = aFetchedResultsController;

【问题讨论】:

    标签: ios xcode properties nsfetchedresultscontroller


    【解决方案1】:

    代码使用 getter 内部的属性,但使用 self.prop = value 语法,它将调用 setter(而不是 getter 内部的 getter)。所以这段代码没有理由生成无限循环。

    无论如何,这是一个相当奇怪的 getter 实现。

    通常情况下,如果 setter 不称自己为 getter,则在 getter 方法中调用 setter 方法是没有问题的。当然如果setter本身调用getter,就会出现无限循环,getter调用setter调用getter等等。

    【讨论】:

    • +1 但是您不能保证从 getter 调用等效的 setter 不会有问题;这样做肯定有点思路不清……
    【解决方案2】:

    因为您使用的是 setter,而不是 getter。

     self.property = something;
    

    这将调用setter:

     [self setProperty:something];
    

    而不是吸气剂:

     [self property];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多