开发者

do I really have to override hash just because I override isEqual: for my subclass?

开发者 https://www.devze.com 2023-02-14 08:25 出处:网络
Apple\'s document says if I override isEqual: then I have to override hash to make sure the hash value should be same for two objects that are consider to be equal by isEqual:

Apple's document says if I override isEqual: then I have to override hash to make sure the hash value should be same for two objects that are consider to be equal by isEqual:

Then I read the docs about hash and below is part of it:

Therefore, either the hash method must not rely on any of the object’s internal state information or you must make sure the object’s internal state information does not change while the object is in the collection.

My customize class MyClass have few of members which are int and bool and NSArray which contains number of MyClass and I want two instance of MyClass to be equal if all of the members are equal.

I have no problem with how to override isEqual: but for hash. Of my understanding, hash should calculate the hash value by combine the members' hash value using bit operation such as XOR or rotational shift.

The problem is how to implement hash in a such way that meets the Apple's requirement that mention at above. Docs says that the hash value should not rely be the internal state(which is the members) but I found I have to use them to compute the value.

Or even do I really need to implement it? Because I sure I will not use this class as a key for NSDictionary and this is the only way I know where hash开发者_运维知识库 is used. Are there any other places where hash is used and I should care about it?


There's two options - either don't rely on the internal state, or ensure that the internal state doesn't change while the object is in a collection.

The second option will allow you to rely on the internal state to generate the hash, but your object must be immutable when in a collection, so that changing it doesn't change its hash.

Collections in Cocoa rely on the hash of an object to perform methods such as containsObject:.

If your object implements a hash that relies on its internal state, is inserted into a collection and then changed, its hash will change, and the collection will lose track of the object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号