A NSDictionary that doesn't copy keys for iPhone 3.0 SDK?
I am using NSDictionary as an associated array (i.e, the keys i am using can be any arbitrary objects). One of the very annoying thing about NSDictionary is that it always make a copy of the key and store it. In my scenario, I will later retrieve the keys from the NSDictionary and do some operations with them. The operation happens to depend on the object identity of the keys. 开发者_高级运维Because the keys i retrieved later are copies of the objects i originally used as keys. The later object identity check fails.
My question is, is there any hashtable-like data structure in the iPhone 3.0 SDK that doesn't make copy of the keys? Thank you.
Outdateboy
If you don't want your key to be copied (or even retained), you can use CFDictionary
and supply a kCFTypeDictionaryKeyCallbacks
or NULL
or customized key callbacks.
To check if objects are equal you should use -isEqual:
instead of ==
.
NSDictionary is toll-free bridged with CFDictionary. So just do:
CFDictionarySetValue((CFDictionaryRef)myMutableDict, key, object);
It's only the Cocoa method that copies the key.
I've recently done the following to achieve a MutableDictionary that doesn't copy it's keys.
-(NSMutableDictionary*)mutableDictionaryWithRetainedKeys {
CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
return CFBridgingRelease(dictionary);
}
If you're keys don't obey NSCopying and you want to avoid compiler warnings when setting key/values use:
CFDictionarySetValue(dictionary, (__bridge const void *)(key), (__bridge const void *)(value));
精彩评论