我正在写一个执行一些CoreData的东西的函数。我想在所有的CoreData操作都执行后,函数只返回。该CoreData的东西涉及到后台前后创建一个对象,然后做一些更多的东西在父上下文:performBlockAndWait创建死锁
+ (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)有人能解释为什么这发生死锁?
and
(2)实现相同功能的正确方法是什么?要求是myFunction
只有在两个块都被执行后才会返回。
谢谢!
但我的要求是两个块已经执行后myFunction的只返回。实质上,它们依赖于正在创建的CoreData对象。所以如果我使用performBlock(异步),那么我没有这个保证。 – user1013725
如果parent.managedObjectContext使用主线程并从主线程调用myFunction,则可以将parent.managedObjectContext中的内容从performBlockAndWait中取出,并在myFunction正文中执行它,紧接在第一个performBlockAndWait之后。 –
啊,是的,我认为这是有效的,谢谢! – user1013725