加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:35:13 所属栏目:百科 来源:网络整理
导读:我看到一些视频/线程,说可以创建“儿童”MOCs – 使用其他MOC作为持续存储的MOC.例如,在您正在使用应用程序的上下文中有用,并希望拥有可以保存/回滚子线程创建的更改的单个主MOC. (从我所了解的一个MOC,它的managedObject必须在同一个线程上使用) 问题是,如
我看到一些视频/线程,说可以创建“儿童”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,或者直接知道您已经在主线程中运行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读