我看过一些视频/线程,它们表示可以创建“子级”MOC——使用其他 MOC 作为其持久存储的 MOC。有用的,例如,在您正在线程化应用程序的上下文中,并希望拥有一个可以保存/回滚子线程创建的更改的主 MOC。 (据我所知,一个 MOC 和它的 managedObjects 必须在同一个线程上使用)
问题是,如何创建子 MOC?我无法找到我正在观看的介绍它们的 WWDC 视频,我所看到的一切都在谈论如何在它们制作完成后使用它们。我可以轻松地分配一个新的 MOC,但我该如何设置它持久存储是另一个 MOC?该引用文献没有显示任何执行此操作的函数!
最佳答案
创建一个您可以完全控制同步的新 MOC。这与调用 init
相同,并且与前父/子关系的行为相同。
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSConfinementConcurrencyType];
您通过设置其属性将一个 MOC 作为另一个 MOC 的父级:
moc.parentContext = someOtherMocThatIsNowMyParent;
在这里, child 选择了 parent 。我确信我的 child 希望他们是 NSManagedObjectContexts。父上下文必须是 NSPrivateQueueConcurrencyType
或 NSMainQueueConcurrencyType
。
您可以创建“绑定(bind)”到私有(private)队列的 MOC:
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
这意味着您只能通过 performBlock
或 performBlockAndWait
API 访问它。您可以从任何线程调用这些方法,因为它们将确保 block 中代码的正确序列化。例如……
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
moc.parentContext = someOtherMocThatIsNowMyParent;
[moc performBlock:^{
// All code running in this block will be automatically serialized
// with respect to all other performBlock or performBlockAndWait
// calls for this same MOC.
// Access "moc" to your heart's content inside these blocks of code.
}];
performBlock
和performBlockAndWait
的区别在于performBlock
会创建一个代码块,并使用 Grand Central Dispatch 调度它来执行在将来的某个时间在某个未知线程上异步。方法调用将立即返回。
performBlockAndWait
将与所有其他 performBlock
调用进行一些神奇的同步,并且当在此之前呈现的所有 block 都完成时,此 block 将执行.调用线程将挂起,直到此调用完成。
您还可以创建一个“绑定(bind)”到主线程的 MOC,就像私有(private)并发一样。
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSMainQueueConcurrencyType];
moc.parentContext = someOtherMocThatIsNowMyParent;
[moc performBlock:^{
// All code running in this block will be automatically serialized
// with respect to all other performBlock or performBlockAndWait
// calls for this same MOC. Furthermore, it will be serialized with
// respect to the main thread as well, so this code will run in the
// main thread -- which is important if you want to do UI work or other
// stuff that requires the main thread.
}];
这意味着只有当您知道自己在主线程上时,您才应该直接访问它,或通过performBlock
或performBlockAndWait
API。
现在,您可以通过 performBlock
方法或直接如果您知道您已经在主线程中运行,就可以使用“主并发”MOC。
关于objective-c - 如何创建子 NSManagedObjectContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12271464/