use*_*725 5 deadlock core-data objective-c nsmanagedobjectcontext ios
我正在编写一个执行一些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仅在两个块都已执行后才返回.
谢谢!
fab*_*ier 11
让我们假设你是myFunction从主线程调用的.让我们想象一下[DatabaseDelegate sharedDelegate].parent.managedObjectContext是在主线程上安排的.
随着[backgroundContext performBlockAndWait:]您安排上下文私人背景队列块.阻止主线程.
使用[.parent.managedObjectContext performBlockAndWait:],您正在主线程上调度块,阻塞专用队列.
但主线程已被阻止.所以块永远不会执行.而且performBlockAndWait:永远不会返回.
僵局.
使用带有完成块的异步调度块.
| 归档时间: |
|
| 查看次数: |
6532 次 |
| 最近记录: |