iPhone iOS如何合并Core Data NSManagedObjectContext?

Ale*_*one 4 iphone core-data objective-c nsmanagedobjectcontext ios

我正在尝试在后台下载一些JSON对象,并且正在进行相当多的多线程.一旦操作完成,我注意到这个断言失败了:

NSAssert([user.managedObjectContext isEqual:[AppUser managedObjectContext]],@"Different contexts");
Run Code Online (Sandbox Code Playgroud)

如何将更改合并到[AppUser managedObjectContext]定义的主上下文中?

Lor*_*o B 11

我真的建议您阅读以下链接输入与显示大型数据集,在核心数据马库斯Zarra.

当你处理线程时,你创建的每个线程都需要有自己的上下文,就像jrturton提供的链接中所写的那样.然后,如果要合并主上下文(在主线程中创建的上下文)和另一个上下文(在上下文中使用的上下文)之间的更改,则需要NSManagedObjectContextDidSaveNotification在主线程中进行侦听

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextHasChanged:) name:NSManagedObjectContextDidSaveNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

和合并一样

- (void)contextHasChanged:(NSNotification*)notification
{
  if ([notification object] == [self mainObjectContext]) return;

  if (![NSThread isMainThread]) {
    [self performSelectorOnMainThread:@selector(contextHasChanged:) withObject:notification waitUntilDone:YES];
    return;
  }

  [[self mainObjectContext] mergeChangesFromContextDidSaveNotification:notification];
}
Run Code Online (Sandbox Code Playgroud)

通知对象包含您在线程上下文中所做的更改.

一些笔记

线程很难实现.我提供的链接使用了NSOperation它的上下文.设置起来非常简单,但是从iOS 5开始,有一些功能可以让您的生活更轻松.

例如,要在不同的线程中创建上下文,您可以执行以下操作:

// create a context with a private queue so access happens on a separate thread.
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
// insert this context into the current context hierarchy
context.parentContext = context;
// execute the block on the queue of the context
[context performBlock:^{

      // do your stuff (e.g. a long import operation)

      // save the context here
      // with parent/child contexts, saving a context pushes the changes out of the current context
      NSError* error = nil;
      [context save:&error];
}];
Run Code Online (Sandbox Code Playgroud)

另外你可以看到doc的文档UIManagedDocument.此类可以很好地集成Core Data,并允许您避免使用Core Data堆栈.

希望能帮助到你.