【发布时间】:2014-05-19 15:31:14
【问题描述】:
我正在开发一个使用核心数据的简单数据库应用程序。记录显示在 tableView 中。为此,我使用了 NSFetchedResultsController。
一切正常,包括删除、更新等。当我更改一些明显与我的数据库结构无关的代码然后再次运行应用程序时,就会出现问题。之后,tableView(有时,并非总是)保持为空。
我发现“numberOfRowsInSection”方法返回的对象数量不正确 (0)。要获取此方法中的行数,我使用以下代码:
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
但是,当我记录以下结果时:
[self.fetchedResultsController.fetchedObjects count];
然后,显示正确数量的对象。
Ergo:NSFetchedResultsController 似乎给了我不正确的 sectionInfo。它以某种方式认为第 0 部分包含 0 个对象,而它包含(例如)7 个对象。
再次重申:我在再次运行应用程序之前更改的代码与核心数据或 fetchedresultscontroller 无关。例如,当我更改字体并再次运行应用程序时,可能会出现问题。
有人知道在哪里/如何修复这个错误吗?
更新:
这就是我执行提取的方式:
-(NSFetchedResultsController *)fetchedResultsController{
NSManagedObjectContext *context = [self managedObjectContext];
if (_fetchedResultsController != nil){
return _fetchedResultsController;
}
NSFetchRequest *fetchrequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entitiy = [NSEntityDescription entityForName:@"JvBTimeRecords" inManagedObjectContext:context];
[fetchrequest setEntity:entitiy];
//sort descriptors
NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:@"date" ascending:NO];
[fetchrequest setSortDescriptors:[NSArray arrayWithObject:sort]];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(project.projectName = %@)", self.searchstring];
[fetchrequest setPredicate:pred];
//fetch only subset. Automatically fetch more as we scroll.
[fetchrequest setFetchBatchSize:20];
_fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchrequest managedObjectContext:context sectionNameKeyPath:nil cacheName:@"CacheA"];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
在 ViewDidLoad 中:
NSError *error;
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]);
//exit(-1); //fail
abort();
}
【问题讨论】:
-
你能发布你如何执行获取请求的代码吗?
-
我更新了代码以显示获取请求。
-
@MartinR 你可能是对的。我将 cacheName 更改为 nil 并且 tableView 再次填充。
-
好的,那么它是重复的。如果使用缓存,则必须在谓词更改时删除缓存。
-
但是,如果在每次与同一实体相关的新提取之前都必须删除缓存,那么缓存有什么用呢?这个想法是:获取一个数据集(在本例中为 JvBTimeRecords)并获取一些数据(那些符合特定标准的数据)。对?为什么在更改谓词之前要删除缓存的数据集?
标签: ios uitableview core-data nsfetchedresultscontroller