objective-ccocoansdictionarynscopying

To be a key of an NSDictionary, must a class also implement isEqual: and hash?


I understand that a class must implement NSCopying in order to be a key of an NSDictionary, but is implementing isEqual: and hash also necessary or advisable?

If yes, why?


Solution

  • Yes.

    Why?

    Consider accessing an element of a dictionary, how does NSDictionary find the object associated with a key? By comparing the key value you provide with the keys in the dictionary.

    It is a rule when you implement isEqual: that you also implement hash, objects which compare equal must have the same hash. Consider further how the dictionary may organise the storage of the key/value pairs, it uses a hash-based storage structure.

    HTH

    Addendum

    Seeing what I guess is a related question you've also asked I will qualify the the above "Yes":

    If a class inherits isEqual: and hash methods which appropriately define equality for itself it need not override the methods with its own versions. In all probability this will not be true if the class directly inherits from NSObject.