Subclassing NSMutableDictionary Subclassing NSMutableDictionary objective-c objective-c

Subclassing NSMutableDictionary


NSMutableDictionary Class Reference says:

In a subclass, you must override both of its primitive methods:

1. setObject:forKey:
2. removeObjectForKey:

You must also override the primitive methods of the NSDictionary class.


NSDictionary Class Reference says:

If you do need to subclass NSDictionary, you need to take into account that is represented by a Class cluster—there are therefore several primitive methods upon which the methods are conceptually based:

1. count
2. objectForKey:
3. keyEnumerator
4. initWithObjects:forKeys:count:

In a subclass, you must override all these methods.

NSDictionary’s other methods operate by invoking one or more of these primitives. The non-primitive methods provide convenient ways of accessing multiple entries at once.


It seems that you need to override all these six methods to make your NSMutableDictionary subclass work perfect.


Here's your problem. NSDictionary (and its mutable counterpart) is part of a class cluster (read more about them here, under the 'Class Cluster' heading), and should not be subclassed because it causes problems such as what you've mentioned (read the subclassing notes in the NSDictionary Class Reference). Whatever it is you need to do, you're going to have a way to extend the classes you want to use in order to do what you want to do. For instance, the above code can easily be placed in a category (read more about categories here).


Are you sure you are not getting the exception when passing in "nil" for a KEY (not a value)?