Search code examples
objective-ccocoansdictionarynscopying

Why must the key of an NSDictionary conform to NSCopying


I noticed that for an object to be a key for an NSDictionary it must conform to NSCopying.

Why is this so? I would understand that all keys must implement hash, but why NSCopying?


Solution

  • Because the keys are copied. You wouldn't want a key to be stored as a reference to the very same object you started with, would you? It would be terrible if d[myThing] = myValue retained a reference to a possibly mutable instance myThing. That would mean that the dictionary could get mutated behind its own back.