iphone - 应用程序设计 : Handling Core Data w/Background Contexts ; Merging w/Notifications Filtered by MOC

标签 iphone ios core-data nsmanagedobjectcontext

我有一个应用程序设计问题,希望有人能提供帮助。

让我们进行一个非常简单的设置:用于显示来自服务器的新闻项的 Core Data 应用程序。

  • 主线程/UI 有一个托管对象上下文,所有 View Controller 都使用它来显示数据。

  • NSOperation 在后台运行,在同一个持久存储上使用它自己的上下文检查服务器。

我想在后台上下文中合并更改,所以我使用 NSManagedObjectContextObjectsDidChangeNotification。

According to the Apple docs :

Several system frameworks use Core Data internally. If you register to receive these notifications from all contexts (by passing nil as the object parameter to an addObserver… method), then you may receive unexpected notifications that are difficult to handle.

所以,我想过滤我在主线程 MOC 中合并的通知,只过滤来自后台操作 MOC 的那些更改。

获取/维护对后台操作 MOC 的引用的最简洁方法是什么,以便我可以将某些内容插入 addObserver 方法并正确过滤通知?我可以想到很多涉及大量耦合的方法,但它们看起来都像是 hack。

有什么建议或想法吗?其他人如何处理这个问题?

最佳答案

这是它在我的应用中的工作方式:

// should be executed on a background thread
- (void)saveWorkerContext {
    if ([_workerContext hasChanges]) {
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];    
        [nc addObserver:self selector:@selector(workerContextDidSave:)
                   name:NSManagedObjectContextDidSaveNotification object:_workerContext];

        NSError *error;
        if (![_workerContext save:&error]) {
            NSAssert(NO, @"Error on save: %@", error);
        }

        [nc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:_workerContext];
    }
}

- (void)workerContextDidSave:(NSNotification *)notification {
    if (_mainContext) {
        [_mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) 
                                       withObject:notification waitUntilDone:NO];
    }
}

关于iphone - 应用程序设计 : Handling Core Data w/Background Contexts ; Merging w/Notifications Filtered by MOC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5860370/

相关文章:

iphone - 如何在原型(prototype) iPhone 应用程序上测试 iAds?

iphone - 在 Objective C 中的实现上下文内部和外部声明静态变量的区别?

ios - 基于对多关系中的属性检索 NSManagedObject 的最快方法

iphone - 如何确定当前连接的 wifi 在 iPhone 或 iPad 中是否安全

ios - 从图像数组创建动画

ios - NSInternalConsistencyException 原因 +entityForName : could not locate an NSManagedObjectModel for entity name

cocoa - 如何将 NSManagedObject 从一个上下文复制或移动到另一个上下文?

iphone - 如何从第一页重新启动基于 Air 的 iOS 应用程序?

iphone - UINavigationController 呈现空白 View

ios - 阻止 iOS 将单词添加到 UITextField 中输入的字典中?