iphone - 核心数据多线程

标签 iphone cocoa cocoa-touch core-data

我的应用程序首先显示一个 TableView ,其数据源是 Core Data SQLite 存储。当应用程序启动时,将创建一个具有自己的存储 Controller 和上下文的辅助线程,以从网络获取存储中数据的更新。但是,对存储产生的任何更改都不会通知 fetchedresults Controller (我推测是因为它有自己的协调器),因此表不会随着存储更改而更新。刷新主线程上下文的最有效方法是什么?我正在考虑跟踪辅助线程上更改的任何对象的 objectID,当辅助线程完成时将它们发送到主线程并调用“[context refreshObject:....] 任何帮助将不胜感激。

最佳答案

在处理表的 NSFetchedResultsController 中,在 viewDidLoadloadView 中注册以获取通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:@"ContextDidSave" object:nil];

当辅助线程准备好新数据时,只需照常保存上下文,然后发布通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ContextDidSave" object:managedObjectContext];

该通知将使用以下方法在您的 NSFetchedResultsController 中处理:

编辑:在与 bbum 进行深入讨论后,修改了以下方法,正确考虑了多线程。

- (void)contextDidSave:(NSNotification *)notification
{

    SEL selector = @selector(mergeChangesFromContextDidSaveNotification:);
    [[[[UIApplication sharedApplication] delegate] managedObjectContext] performSelectorOnMainThread:selector withObject:notification waitUntilDone:YES];

}

对于 UI 更新,可以使用 NSFetchedResultsController 委托(delegate)方法自动完成。

最后,请记住在 NSFetchedResultsControllerdealloc 方法中添加以下内容:

[[NSNotificationCenter defaultCenter] removeObserver:self];

关于iphone - 核心数据多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2637141/

相关文章:

iPhone 打开时放大页面

iphone - 旋转UIImage自定义角度

ios - Xcode - 如何修复 'NSUnknownKeyException',原因 : … this class is not key value coding-compliant for the key X"error?

objective-c - Interface Builder 不显示 IBActions

iphone - 使用 iPhone 地址簿联系人创建电子名片

iphone - 如何在 iphone 中使用 DUKPT 和 3DES 算法为读卡器应用程序加密、解密数据?

ios - 使用 Vuforia SDK 在 Unity 中构建的 AR App 中的问题

cocoa - "helper app"和 GUI 应用程序如何相互通信?

ios - 可与 SpriteKit 的 labelNodeWithFontNamed 方法一起使用的字体列表

ios - CGAffineTransform 旋转大小问题