我目前遇到一个问题,当 FRC 的 fetchRequest 上的 fetchLimit 为 4 时,使用 NSFetchedResultsController 的 UITableViewController/UITableView 显示大约 86 个项目。我知道 86 个项目满足 fetch 本身,并且我知道它们出现的原因是因为 didChangeObject: atIndexPath... 被 86 个中的每一个调用,并且我按默认实现方式插入。
我的问题是为什么 fetchLimit 不限制 NSFetchedResultsController 尝试“更改”(在这种情况下插入)的对象数量?
我的应用程序用例是第一个选项卡显示我在应用程序启动时(在侧线程上)获得的典型提要项目。我将它们保存在单独的上下文中的 CoreData 中,最终合并到主线程的上下文中并针对更改的内容启动 FRC 回调。我的问题专门针对不存在任何项目的初始情况。
这是我的fetchRequest:
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
fetchRequest.entity = [NSEntityDescription entityForName:ENTITY_CONTENT_ITEM inManagedObjectContext:managedObjectContext];
// Set a limit on the number of items returned
[fetchRequest setFetchLimit:4];
// Set a Predicate to limit the fetch to featured items only
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"featured == YES AND contentType == %d", contentType]];
// Set the sort descriptors
NSSortDescriptor *sortDateDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"sortDate" ascending:NO] autorelease];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDateDescriptor]];
上面的 contentType 只是一种区分应该在此选项卡与其他选项卡中显示的内容的方法。Featured 是项目的布尔属性,它更像是一个用于显示目的的开关。
这是我的didChangeObject:
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[tableView cellForRowAtIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// Reloading the section inserts a new row and ensures that titles are updated appropriately.
[tableView reloadSections:[NSIndexSet indexSetWithIndex:newIndexPath.section] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
我知道这个问题很难回答,但即使是解释 FRC 如何决定调用 didChangeObject 的次数也会非常有帮助。