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

objective-c – NSManagedObjectContext混淆

我正在学习CoreData.显然,你所包含的主要类之一是NSManagedobjectContext.我不清楚这个的确切作用.从我读过的文章中,您似乎可以拥有多个NSManagedobjectContexts.这是否意味着NSManagedobjectContext基本上是后端的副本?

当存在多个不同的副本时,这将如何解决为一致的后端?

那么,基本上有两个问题:

NSManagedContext是后端数据库的副本吗?

和…

例如,假设我在上下文A中进行了更改,并在上下文B中进行了一些其他更改.然后我先调用保存在A上,然后是B? B会占上风吗?

谢谢

解决方法

NSManagedobjectContext不是后端数据库的副本. documentation将其描述为便笺簿

An instance of NSManagedobjectContext represents a single “object
space” or scratch pad in an application. Its primary responsibility is
to manage a collection of managed objects. These objects form a group
of related model objects that represent an internally consistent view
of one or more persistent stores. A single managed object instance
exists in one and only one context,but multiple copies of an object
can exist in different contexts. Thus object uniquing is scoped to a
particular context.

NSManagedobjectContext只是以事务方式更改托管对象的临时位置.当您对上下文中的对象进行更改时,它不会影响后端数据库,直到您保存上下文,并且如您所知,您可以拥有多个上下文,您可以对其进行更改,这对于concurrency非常重要.

对于问题2,谁占优势的答案将取决于您为上下文设置的merge policy以及最后一个将被称为B的那个.以下是可以设置的合并策略,这将影响要保存的第二个上下文.

NSErrorMergePolicyType
Specifies a policy that causes a save to fail
if there are any merge conflicts.

NSMergeByPropertyStoreTrumpMergePolicyType
Specifies a policy that
merges conflicts between the persistent store’s version of the object
and the current in-memory version,giving priority to external
changes.

NSMergeByPropertyObjectTrumpMergePolicyType
Specifies a policy that merges conflicts between the persistent store’s version
of the object and the current in-memory version,giving priority to
in-memory changes.

NSOverwriteMergePolicyType
Specifies a policy that
overwrites state in the persistent store for the changed objects in
conflict.

NSRollbackMergePolicyType Specifies a policy that discards in-memory state changes for objects in conflict.

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

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

相关推荐