创建一个新的 MOC,您可以完全控制同步。这与调用相同init
以及与前亲子关系相同的行为。
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSConfinementConcurrencyType];
您可以通过设置 MOC 的属性来将其作为另一个 MOC 的父级:
moc.parentContext = someOtherMocThatIsNowMyParent;
在这里,孩子选择父母。我确信我的孩子希望他们是 NSManagedObjectContexts。父上下文必须是NSPrivateQueueConcurrencyType
or NSMainQueueConcurrencyType
.
您可以创建一个“绑定”到专用队列的 MOC:
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
这意味着您只能通过以下方式访问它performBlock
or performBlockAndWait
API。您可以从任何线程调用这些方法,因为它们将确保块中代码的正确序列化。例如...
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
and performBlockAndWait
就是它performBlock
将创建一个代码块,并使用 Grand Central Dispatch 安排它在未来某个时间在某个未知线程上异步执行。方法调用将立即返回。
performBlockAndWait
会与所有其他人进行一些神奇的同步performBlock
调用,并且当在此块之前出现的所有块都完成时,该块将执行。调用线程将挂起,直到该调用完成。
您还可以创建一个“绑定”到主线程的 MOC,就像私有并发一样。
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.
}];
这意味着只有当您知道自己位于主线程上时才应该直接访问它,or通过performBlock
or performBlockAndWait
API.
现在,您可以通过以下方式使用“主并发”MOC:performBlock
方法,或者直接if你知道你已经在主线程中运行了。