Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

iphone

hash

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?

like image 718
Bryan Chen Avatar asked Oct 12 '22 14:10

Bryan Chen


1 Answers

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.

like image 63
Jasarien Avatar answered Oct 30 '22 20:10

Jasarien