我插入并保存托管对象:
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
MyCity* city = (MyCity*)[NSEntityDescription insertNewObjectForEntityForName:@"City" inManagedObjectContext:context];
city.cityId = dict[@"id"];
city.cityName = dict[@"name"];
NSError *error;
if (![context save:&error]) {
NSLog(@"error: %@", [error localizedDescription]);
}
我执行FRC请求:
_fetchedResultsController = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
这是我的FRC:
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"City"
inManagedObjectContext: context];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"cityName" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, nil];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:10];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath: @"cityName"
cacheName: @"cache"];
[self setFetchedResultsController: theFetchedResultsController];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
在
performFetch
之后,我看到:_fetchedResultsController.fetchedObjects //array of MyCity objects
_fetchedResultsController.sections //empty array
为什么_fetchedResultsController.sections为空?
当我不使用
[context save:&error]
时,我可以在_fetchedResultsController.sections中看到对象数组。在我的代码中保存上下文有问题吗?如何保存nsmanagedobject和nsmanagedcontext?
最佳答案
也许dict
为空,所以cityName
为空,并且没有节头。
另外,您应该持有对托管对象上下文的引用,而不是反复访问应用程序委托来获取它。
我还建议您在不使用fetchBatchSize
和cache:nil
的情况下测试您的代码,并在以后进行优化。
另请注意,通常的模式是在返回FRC之前延迟创建FRC时进行访存。然后,您可以对其进行nil
生成以生成提取,也可以在现有实例上调用performFetch
。
关于ios - FetchedResultsController中没有任何节,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24754958/