Ked*_*ape 8 core-data objective-c uitableview nsfetchedresultscontroller ios
我有一个UITableView(有自定义单元格,如果重要的话)连接到一个NSFetchedResultsController.我的应用程序也使用推送通知.当远程通知到达时,我分两个阶段更新我的(核心)数据模型:
1)获取标题(带有一些自定义数据)并将其存储为新的核心数据Entity.我在这里打电话NSManagedObjectContext save().NSFetchedResultsController拿起插入并didChangeObject用NSFetchedResultsChangeType=来激活它的委托方法NSFetchedResultsChangeInsert.tableview即时更新.(插入一个新行)
2)通过NSURLSession将其插入上面Entity并再次调用,下载与该单元相关的更多内容save() method.NSFetchedResultsController再次获取更新并didChangeObject使用NSFetchedResultsChangeType= 触发它的委托方法NSFetchedResultsChangeUpdate.这是我称之为configureCell方法的地方.tableView已更新,但具有大约10秒的一致延迟.
在这两个阶段(下载环境保存更新的tableview)需要被显示的数据也已经由核心数据持久化.(例如,在我的configureCell..方法中,我知道我没有设置任何细胞标签nil或类似的.
我的NSFetchedResultsController委托方法:
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.mainTableView beginUpdates];
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.mainTableView endUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.mainTableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:(MessageTableViewCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
}
}
Run Code Online (Sandbox Code Playgroud)
我在里面尝试过的其他事情 case NSFetchedResultsChangeUpdate:
processPendingChanges在上下文之前尝试调用savereloadRowsAtIndexPaths而不是configureCell直接打电话beginUpdates和endUpdates(虽然我已经有一对应该做的工作)[tableView reloadData]numberOfRowsInSection 不是0!NSFetchedResultsController委托方法只是在主线程上运行.简而言之,正确调用所有(?)正确的委托方法.然而,在更新单元格时,我看到一致的~10秒延迟.但是,插入几乎是瞬间完成的.有任何想法吗?
@Paulw11 的评论让dispatch_async...我朝着正确的方向前进。问题在于,我一直ManagedObjectContext在两个不同的线程中使用同一个对象,即使它们不同时访问它。一旦我将我的save调用(在后台线程上)调度到主队列上(通过将其包装在 内部dispatch_async(dispatch_get_main_queue,^{ UIUpdate code here });),延迟就消失了。一种可能的解释是,调用save后台线程会导致在后台线程上调用委托方法。
不管怎样,回到解决方案——永远不要ManagedObjectContext在多个线程之间共享同一个对象。如果您要在多个线程中更新核心日期,请使用父/子上下文关系。NSFetchedResultsController这种模式也能很好地发挥作用。
| 归档时间: |
|
| 查看次数: |
715 次 |
| 最近记录: |