我正在编写一个执行一些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;
}
Run Code Online (Sandbox Code Playgroud)
我希望回归只发生在之后[queue addOperation:someOperation].这似乎适用于大多数情况,但我有一个案例,当这个函数永远不会返回.好像它已陷入僵局,我怀疑这是因为performBlockAndWait.
我的问题是:
(1)有人可以解释为什么会出现这种僵局吗?
和
(2)实现相同功能的正确方法是什么?要求是myFunction仅在两个块都已执行后才返回.
谢谢!