Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 881
cfischer Avatar asked Dec 15 '22 15:12

cfischer


2 Answers

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.

like image 178
matt Avatar answered Jan 29 '23 16:01

matt


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:

  1. Copy keys to prevent them from changing.
  2. Demand that keys are immutable.

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.

like image 26
Avt Avatar answered Jan 29 '23 17:01

Avt