微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,或者直接知道您已经在主线程中运行.

原文地址:https://www.jb51.cc/c/114367.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐