objective-c - NSManagedObjectContext 困惑

标签 objective-c ios cocoa-touch core-data nsmanagedobjectcontext

我正在学习 CoreData。显然,您使用的主要类之一是 NSManagedObjectContext。我不清楚这个的确切作用。从我读过的文章来看,您似乎可以拥有多个 NSManagedObjectContext。这是否意味着 NSManagedObjectContext 基本上是后端的副本?

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

所以,基本上有 2 个问题:

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.

关于objective-c - NSManagedObjectContext 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8791203/

相关文章:

ios - 使用 boundingRectWithSize :options:attributes:context: 创建动态标签

iphone - 在线存储我的 ObJ-C 类(class)。 (亚马逊网络服务?)

ios - 检查坐标有效性 - UITextField - iOS

iphone - 定义将由类方法使用的私有(private)方法 - Objective C

objective-c - Swift 枚举 Objective-C 中的关联值

ios - 使用 mailto : URLs 发送电子邮件

ios - NSPredicate 数组包含问题

iphone - 在应用程序委托(delegate)之外注册远程通知

ios - 在一个 UITableViewController 中有两个 UITableView

ios - 如何在 iOS 上托管 HTTP Web 服务?