Using objects as keys for NSMutableDictionary

Nov 4, 2011   #cocoa  #ios 

When adding an object as a key to a NSMutableDictionary with setObject:forKey:, the dictionary copies the key object by sending a copyWithZone: message to it.

So your key objects must respond to this selector. This protects the dictionary from key changes that take place outside the dictionary.

In many cases you will want to retrieve the values of the dictionary by passing your key object reference to objectForKey:. So copying the key when adding it to the dictionary is not a good idea.

If your key objects are immutable, it is perfectly safe to have the following implementation for copyWithZone::

- (id)copyWithZone:(NSZone*)zone {
    return self;

This ensures that the object itself instead of a copy is used as a key in the dictionary.