问题描述
假设变量A和B在同一个托管对象上下文中保存托管对象的实例。我需要确保它们与持久存储中相同的记录相关联。核心数据编程中的部分指南说:
Let's say variable A and B hold instances of managed objects in the same managed object context. I need to make sure that they are associated with the same "record" in the persistent store. The section on Faulting and Uniquing in the Core Data Programming Guide says that:
从这里,似乎指针比较足以满足我的目的。
From this, it seems that a pointer comparison is sufficient for my purpose. Or does it ever make sense to use isEqual: to compare managed objects in the same context?
推荐答案
使用 == 来确定两个指针是否指向同一个对象。使用 -isEqual
来确定两个对象是否为等于,其中相等的概念取决于被比较的对象。 -isEqual:
通常会比较 -hash
方法返回的值。我之前写过,如果两个托管对象包含相同的值,则 -isEqual:
可能会返回true。这显然是不对的。文档中有一些注意事项,确保可变对象的哈希值在集合中不会改变,并且知道给定对象是否在集合中可能很困难。看起来,管理对象的哈希不依赖于该对象包含的数据,并且更有可能它连接到关于对象的不可变的东西;对象的 -objectID
值似乎是一个可能的候选人。
Use ==
to determine if two pointers point to the same object. Use -isEqual
to determine if two objects are "equal", where the notion of equality depends on the objects being compared. -isEqual:
normally compares the values returned by the -hash
method. I wrote previously that it seemed possible that -isEqual:
might return true if two managed objects contain the same values. That's clearly not right. There are some caveats in the docs about making sure that the hash value for a mutable object doesn't change while it's in a collection, and that knowing whether a given object is in a collection can be difficult. It seems certain that the hash for a managed object doesn't depend on the data that that object contains, and much more likely that it's connected to something immutable about the object; the object's -objectID
value seems a likely candidate.
鉴于这一切,我改变了我的意见; )。每个记录只在给定的上下文中表示一次,因此 ==
可能是安全的,但 -isEqual:
更好地表达你的意图。
Given all that, I'm changing my opinion ;-). Each record is only represented once in a given context, so ==
is probably safe, but -isEqual:
seems to better express your intention.
这篇关于我应该使用==或[NSManagedObject isEqual:]来比较同一上下文中的托管对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!