多个NSManagedObjectContexts问题

时间:2014-04-22 16:43:59

标签: ios objective-c multithreading core-data

我在两个NSManagedObjectContext之间实现父/子关系时遇到问题。我的应用程序从Web服务导入了大量数据,这些数据在保存上下文时导致UI延迟。所以在我的AppDelegate中,我用NSPrivateQueueConcurrencyType创建了一个父上下文(master):

- (NSManagedObjectContext *)masterMOC
{
  if (_masterMOC != nil) {
      return _masterMOC;
  }

  NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
  if (coordinator != nil) {
    _masterMOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [_masterMOC setPersistentStoreCoordinator:coordinator];
  }
  return _masterMOC;
}

...和NSMainQueueConcurrencyType的子上下文(main)。我将主MOC的parentContext设置为masterMOC:

- (NSManagedObjectContext *)mainMOC
{
  if (_mainMOC != nil) {
    return _mainMOC;
  }

  _mainMOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
  [_mainMOC setUndoManager:nil];
  [_mainMOC setParentContext:[self masterMOC]];

  return _mainMOC;
}

在我的applicationDidFinishLaunching中,我启动了一个查询Web服务的导入操作,并将结果保存在master(PrivateQueue)上下文中。我还注册了NSManagedObjectContextDidSaveNotification,并尝试将这些更改合并到子mainMOC中。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  [notificationCenter addObserver:self selector:@selector(contextChanged:) name:NSManagedObjectContextDidSaveNotification object:self.masterMOC];

  RequestHandler *handler = [[RequestHandler alloc] initWithManagedObjectContext:self.masterMOC];
  [handler importAllViews];

  ...

  return YES;
}

- (void) contextChanged: (NSNotification *) notification
{
  // Only interested in merging from master into main.
  if ([notification object] != self.masterMOC) return;

  [self.mainMOC performBlock:^{
    [self.mainMOC mergeChangesFromContextDidSaveNotification:notification];
  }];
}

RequestHandler类有一个saveContext方法,可以将主上下文保存在正确的线程上:

@implementation KDBRequestHandler

...

- (void) saveContext
{    
  [self.managedObjectContext performBlock:^{
    NSError *error;
    if (![self.managedObjectContext save:&error]) {
        [NSException raise:@"Unable to save build details." format:@"Error saving context: %@", error];
    }
  }];
}

... 

@end

我已经验证了导入是否正确使用Instruments在后台线程上保存其对象。 我的问题在于具有NSMainQueueConcurrencyType的子托管对象上下文。在启动导入后,应用程序didFinishLaunching按标准初始化UI。视图控制器被分配了mainMOC。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Override point for customization after application launch.
  if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
    UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
    UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
    splitViewController.delegate = (id)navigationController.topViewController;

    UINavigationController *masterNavigationController = splitViewController.viewControllers[0];
    KDBMasterViewController *controller = (KDBMasterViewController *)masterNavigationController.topViewController;
    controller.managedObjectContext = self.mainMOC;
  } else {
    UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
    KDBMasterViewController *controller = (KDBMasterViewController *)navigationController.topViewController;
    controller.managedObjectContext = self.mainMOC;
  }

  return YES;
}

MasterViewController本质上是在创建核心数据项目时为您创建的样板控制器。它的fetchedResultsController最终在mainMOC上执行其工作,因此是主线程。

- (NSFetchedResultsController *)fetchedResultsController
{
  if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
  }

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  // Edit the entity name as appropriate.
  NSEntityDescription *entity = [NSEntityDescription entityForName:@"Job" inManagedObjectContext:self.managedObjectContext];
  [fetchRequest setEntity:entity];

  // Set the batch size to a suitable number.
  [fetchRequest setFetchBatchSize:20];

  // Edit the sort key as appropriate.
  NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
  NSArray *sortDescriptors = @[sortDescriptor];

  [fetchRequest setSortDescriptors:sortDescriptors];

  // Edit the section name key path and cache name if appropriate.
  // nil for section name key path means "no sections".
  NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
  aFetchedResultsController.delegate = self;
  self.fetchedResultsController = aFetchedResultsController;

  NSError *error = nil;
  if (![self.fetchedResultsController performFetch:&error]) {
    // Replace this implementation with code to handle the error appropriately.
    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }

  return _fetchedResultsController;
}

在初始加载时,数据库是新的并且空的一切都按预期工作。数据在后台下载并按预期填充在MasterViewController的UITableView中。但是在后续运行中,应用程序经常在MasterViewController的fetchedResultsController中崩溃。提取失败并显示以下错误:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Job''
*** First throw call stack:
(
0   CoreFoundation                      0x01c6a1e4 __exceptionPreprocess + 180
1   libobjc.A.dylib                     0x019678e5 objc_exception_throw + 44
2   CoreData                            0x002c6a1b +[NSEntityDescription entityForName:inManagedObjectContext:] + 251
3   JMobile                       0x00032ad4 -[KDBMasterViewController fetchedResultsController] + 340
4   JMobile                       0x00031d6e -[KDBMasterViewController numberOfSectionsInTableView:] + 78
5   UIKit                               0x0088e712 -[UITableViewRowData(UITableViewRowDataPrivate) _updateNumSections] + 102
6   UIKit                               0x0088f513 -[UITableViewRowData invalidateAllSections] + 69
7   UIKit                               0x006fa6ea -[UITableView _updateRowData] + 197
....

由于崩溃不会100%发生,我怀疑是并发问题。我通过注意,当fetchedResultsController查询时, mainMOC的父上下文为nil确认。在尝试查询之前,如何确保子上下文(mainMOC)与父项正确设置它?

1 个答案:

答案 0 :(得分:1)

有一个竞争条件访问您的mainMOC
在将观察者添加到masterMOC的保存之后以及开始导入之前添加行[self mainMOC];将在MOC初始化竞赛中工作。

您可以阅读THIS以了解类似案例中的竞争条件(关于哪个线程并行访问您的上下文)。

Apple提供的模板代码很好,只有一个线程初始化你的上下文(非临时的),否则,你应该使用某种线程锁定机制同步初始化。