我正在编写一个执行一些 CoreData 东西的函数。我希望该函数仅在所有 CoreData 操作都执行后才返回。CoreData 的东西包括在后台上下文中创建一个对象,然后在父上下文中做更多的事情:
+ (void) myFunction
    NSManagedObjectContext *backgroundContext = [DatabaseDelegate sharedDelegate].backgroundContext;
    [backgroundContext performBlockAndWait:^{
      MyObject *bla = create_my_object_in:backgroundContext;
      [backgroundContext obtainPermanentIDsForObjects:[[backgroundContext insertedObjects] allObjects] error:nil];
      [backgroundContext save:nil];
      [[DatabaseDelegate sharedDelegate].parent.managedObjectContext performBlockAndWait:^{
        [[DatabaseDelegate sharedDelegate].parent updateChangeCount:UIDocumentChangeDone];
        // Do some more stuff
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [queue addOperation:someOperation];
      }];
    }];
   return;
}
我希望返回只发生在[queue addOperation:someOperation]. 这似乎在大多数情况下都有效,但我遇到过一个情况,该函数从未返回。似乎它陷入了僵局,我怀疑这是因为performBlockAndWait.
我的问题是:
(1)有人可以解释为什么会发生这种死锁吗?
和
(2) 实现相同功能的正确方法是什么?要求是myFunction仅在两个块都执行后才返回。
谢谢!