Ron*_*gge 11 xcode core-data objective-c nsmanagedobjectcontext ios
我看过一些视频/帖子说可以创建'儿童'MOCs - 使用其他MOC作为持久存储的MOC.例如,在您正在线程化应用程序的上下文中,并希望拥有一个可以保存/回滚子线程创建的更改的主MOC时很有用.(根据我的理解,MOC和它的托管对象必须都在同一个线程上使用)
问题是,我如何创建一个儿童MOC?我无法追踪我正在观看的WWDC视频介绍它们,我所看到的一切都在讨论如何使用它们.我可以很容易地分配一个新的MOC,但我该怎么设置它持久存储是另一个MOC?该引用没有显示任何功能!
Jod*_*ins 36
创建一个新的MOC,您可以完全控制同步.这与调用init和与父/子关系相同的行为相同.
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSConfinementConcurrencyType];
Run Code Online (Sandbox Code Playgroud)
您通过设置其属性将MOC提交给另一个MOC:
moc.parentContext = someOtherMocThatIsNowMyParent;
Run Code Online (Sandbox Code Playgroud)
在这里,孩子选择父母.我相信我的孩子们希望他们是NSManagedObjectContexts.父上下文必须是NSPrivateQueueConcurrencyType或者NSMainQueueConcurrencyType.
您可以创建一个"绑定"到私有队列的MOC:
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
Run Code Online (Sandbox Code Playgroud)
这意味着您只能通过performBlock或performBlockAndWaitAPI 访问它.您可以从任何线程调用这些方法,因为它们将确保块中代码的正确序列化.例如...
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.
}];
Run Code Online (Sandbox Code Playgroud)
之间的区别performBlock,并performBlockAndWait是performBlock将创建的代码块,并与大中央调度安排它要在未来的一段时间内异步执行,在一些不知名的线程.方法调用将立即返回.
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.
}];
Run Code Online (Sandbox Code Playgroud)
这意味着你只应该直接访问它,如果你知道你是在主线程,或通过performBlock或performBlockAndWaitAPI.
现在,您可以使用"主并发" MOC要么通过performBlock方法或直接,如果你知道你已经在主线程中运行.
| 归档时间: |
|
| 查看次数: |
7847 次 |
| 最近记录: |