Cocoa's NSDictionary: why are keys copied?

前端 未结 3 1367
小蘑菇
小蘑菇 2021-02-05 06:33

All objects used as keys in NS(Mutable)Dictionaries must support the NSCopying protocol, and those objects are copied when they\'re used in the dictionary.

I frequently

3条回答
  •  再見小時候
    2021-02-05 07:04

    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.

提交回复
热议问题