NSFetchedResultsController返回错误的部分信息

时间:2014-05-19 15:31:14

标签: ios uitableview core-data nsfetchedresultscontroller

我正在开发一个使用核心数据的简单数据库应用程序。记录显示在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();
}

1 个答案:

答案 0 :(得分:0)

不应该这样:

id <NSFetchedResultsController> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];

是吗?

id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];