objective-c – 如何创建一个小孩NSManagedObjectContext?

我看到一些视频/线程,说可以创建“儿童”MOCs – 使用其他MOC作为持续存储的MOC.例如,在您正在使用应用程序的上下文中有用,并希望拥有可以保存/回滚子线程创建的更改的单个主MOC. (从我所了解的一个MOC,它的managedobject必须在同一个线程上使用)

问题是,如何创建一个小孩MOC?我无法跟踪我正在观看的WWDC视频,介绍了它们,我所看到的一切都在谈论如何使用它们,我可以轻松地分配一个新的MOC,但是如何设置它持久存储是另一个MOC?引用不显示任何这样做的功能

解决方法

创建一个新的MOC,您可以完全控制同步.这与调用init相同,并且与pre-parent / child关系相同.
NSManagedobjectContext *moc = [[NSManagedobjectContext alloc]
       initWithConcurrencyType:NSConfinementConcurrencyType];

您通过设置其属性将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,或者直接知道您已经在主线程中运行.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...