gpt4 book ai didi

objective-c - NSManagedObjectContext 困惑

转载 作者:可可西里 更新时间:2023-11-01 03:28:13 24 4
gpt4 key购买 nike

我正在学习 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com