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;
答案 0 :(得分:3)
代码使用getter中的属性,但使用self.prop = value
语法,它将调用 setter (而不是getter中的getter)。所以这个代码没有理由产生无限循环。
无论如何,这是一个非常奇怪的getter实现。
通常,如果setter没有将getter方法称为getter,那么在getter方法中调用setter方法是没有问题的。当然,如果setter本身调用getter,那么你将拥有无限循环,getter调用setter调用getter等等。
答案 1 :(得分:2)
因为你使用的是setter,而不是getter。
self.property = something;
这将调用setter:
[self setProperty:something];
而不是吸气剂:
[self property];