我是iOS的初学者。当我将Core Data用于我的示例项目时,它会给我一个线程错误。
请帮我解决这个错误。
这是我的代码:
-(NSFetchedResultsController*)fetchedResultController{
if (self.fetchedResultController != nil ) {
return self.fetchedResultController;
}
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Recepie" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"recepieName" ascending:YES];
NSArray *sortDescriptorArray = [[NSArray alloc]initWithObjects:sortDescriptor,nil];
request.sortDescriptors = sortDescriptorArray;
self.fetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest: request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultController.delegate = self;
return self.fetchedResultController;
}
答案 0 :(得分:6)
使用像这样的点符号引用属性时
if (self.fetchedResultController != nil ) {
return self.fetchedResultController;
}
它等同于调用[self fetchedResultController]
方法(这是此属性的getter)。当你这样做时,你已经 在getter中,所以该方法无限调用自身,导致Stack overflow error。
您不应使用点表示法来获取属性值(使用setter是正常的)。改为使用backing variable:
if(_fetchedResultController != nil) {
return _fetchedResultController;
}
答案 1 :(得分:0)
您能否请尝试以下代码。
-(NSFetchedResultsController*)fetchedResultController{
if (self.fetchedResultController != nil ) {
return self.fetchedResultController;
}
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Recepie" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"recepieName" ascending:YES];
NSArray *sortDescriptorArray = [[NSArray alloc]initWithObjects:sortDescriptor,nil];
request.sortDescriptors = sortDescriptorArray;
self.fetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest: request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultController.delegate = self;
error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return self.fetchedResultController;
}