创建一个您可以完全控制同步的新 MOC。这与调用 init 相同,与前父/子关系的行为相同。
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSConfinementConcurrencyType];
通过设置 MOC 的属性,您可以将 MOC 设置为另一个 MOC:
moc.parentContext = someOtherMocThatIsNowMyParent;
在这里,孩子选择父母。我确定我的孩子希望他们是 NSManagedObjectContexts。父上下文必须是 NSPrivateQueueConcurrencyType 或 NSMainQueueConcurrencyType。
您可以创建一个“绑定”到私有队列的 MOC:
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
这意味着您只能通过performBlock 或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 和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.
}];
这意味着只有当你知道你在主线程上时,你才应该直接访问它,或通过performBlock或performBlockAndWait API。
现在,您可以通过performBlock 方法使用“主并发”MOC,或者直接如果您知道自己已经在主线程中运行。