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
?
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.
NSDictionary
guaranties that if you store a value with some key x
this key is fixed and you can retrieve this value with the equivalent key y
(y.isEqual(x) == YES
). There are only two possibilities to do so:
Apple decided that for most cases coping keys is better.
In case you need a dictionary were keys are not copied (for example keys do not implement NSCopying or coping is too expensive) you can use NSMapTable. For example you can use
[NSMapTable strongToStrongObjectsMapTable]
to store keys and values as a strong references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With