Cocoa's NSDictionary: why are keys copied?

不羁的心 提交于 2019-12-03 01:28:47
Dirk

The copy ensures that the values used as keys don't change "underhand" while being used as keys. Consider the example of a mutable string:

NSMutableString* key = ... 
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];

[dict setObject: ... forKey: key];

Let's assume that the dictionary did not copy the key, but instead just retained it. If now, at some later point, the original string is modified, then it is very likely that you are not going to find your stored value in the dictionary again even if you use the very same key object (i.e., the one key points to in the example above).

In order to protect yourself against such a mistake, the dictionary copies all keys.

Note, by the way, that it is simple enough to define -copyWithZone: as just doing return [self retain]. This is allowed and good code if your object is immutable, and the NSCopying contract is specifically designed such that the object returned has to be (sorta, kinda) immutable:

Implement NSCopying by retaining the original instead of creating a new copy when the class and its contents are immutable.

(from NSCopying Reference)

and

The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object; otherwise the exact nature of the copy is determined by the class.

(from -copyWithZone: Reference)

Even if your objects are not immutable, you might get away with that implementation if you only ever use identity-based equality/hash implementations, i.e., implementations which are not affected in any way by the object's internal state.

garageàtrois

If you want to store pointers as keys then you'll need to wrap them in a NSValue object with +valueWithPointer:.

Since iOS 6 if you want to use pointers as keys, you can use the NSMapTable object, see http://nshipster.com/nshashtable-and-nsmaptable/

You can specify whether keys and/or values are stongly or weakly held:

NSMapTable *mapTable = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory
                                         valueOptions:NSMapTableWeakMemory];

Another option that could be appropriate sometimes is to use NSCache, which holds keys strongly and is actually thread-safe.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!