什么是NSObject isEqual:和哈希默认函数? [英] What is the NSObject isEqual: and hash default function?
问题描述
我有一个数据库模型类,它是一个NSObject
.我在NSMutableArray
中有一组这些对象.我使用indexOfObject:
查找匹配项.问题在于模型对象的内存地址发生了变化.因此,我重写了hash
方法以返回模型的行ID.但是,这不能解决问题.我还必须重写isEqual:
方法以比较hash
方法的值.
I have a database model class that is a NSObject
. I have a set of these objects in a NSMutableArray
. I use indexOfObject:
to find a match. Problem is the model object's memory address changes. So I am overriding the hash
method to return the model's row ID. This however does not fix it. I also have to override the isEqual:
method to compare the value of the hash
method.
默认情况下,isEqual:
方法用于确定相等性的是什么?
What does the isEqual:
method use to determine equality by default?
我假设它使用内存地址.阅读 isEqual:
文档,我认为它使用了hash
方法中的值.显然,情况并非如此,因为我尝试覆盖该值并不能解决我最初的问题.
I'm assuming it uses the memory address. After reading the isEqual:
documentation I thought it used the value from the hash
method. Obviously, that is not the case as my attempt to override that value did not solve my initial problem.
推荐答案
您已经正确地猜到了,NSObject
的默认isEqual:
行为是比较对象的内存地址.奇怪的是,目前自省文档,其中指出:
As you've correctly guessed, NSObject
's default isEqual:
behaviour is comparing the memory address of the object. Strangely, this is not presently documented in the NSObject Class Reference, but it is documented in the Introspection documentation, which states:
isEqual:
的默认NSObject
实现仅检查指针是否相等.
The default
NSObject
implementation ofisEqual:
simply checks for pointer equality.
当然,正如您毫无疑问地知道的那样,NSObject
的子类可以覆盖isEqual:
以表现不同.例如,NSString
的isEqual:
方法在传递另一个NSString
时,将首先检查地址,然后检查字符串之间的确切文字匹配.
Of course, as you are doubtless aware, subclasses of NSObject
can override isEqual:
to behave differently. For example, NSString
's isEqual:
method, when passed another NSString
, will first check the address and then check for an exact literal match between the strings.
这篇关于什么是NSObject isEqual:和哈希默认函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!