Object keys with NSMutableDictionary (Objective-C)

故事扮演 提交于 2019-12-04 04:31:59
DarkDust

Dictionary keys are always copied. So you simply need to implement the NSCopying protocol for your class, which is just the copyWithZone: method.

Additionally you should implement the isEqual: method for your class.

Edit: How to implement your copyWithZone: depends on a number of factors (main factor: deep vs. shallow copy). See Apple's Implementing Object Copy guide and this SO answer.

kennytm

You could turn an id into an NSValue with:

NSValue* value = [NSValue valueWithNonretainedObject:object];
...
id object_ = [value nonretainedObjectValue];

but you need to manage the ownership outside of the dictionary. This is going to be a mess. It's better to adopt NSCopying.


There is also a 4th option: use a CFDictionary, which allows the object only can be CFRetain/CFReleased, not copied.

CFMutableDictionaryRef dict = CFDictionaryCreateMutable(
     kCFAllocatorDefault, 0,
     &kCFTypeDictionaryKeyCallBacks,
     &kCFTypeDictionaryValueCallBacks
);

...

CFDictionarySetValue(dict, myObjectA, value);
...

CFRelease(dict);

And if you're programming for Mac or iOS 6 and above, try NSMapTable.

NSMapTable* dict = [[NSMapTable mapTableWithStrongToStrongObjects] retain];
...
[dict setObject:@"?" forKey:foo];
...
[dict release];

In iOS 6 you can use NSMapTable (https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/NSMapTable_class/Reference/NSMapTable.html), which allows you to chose weak/strong attributes for the keys and objects.

You don't need to wrap your object using NSValue. What you have will work except you're missing a piece. For myObjectA's class you need to adopt the NSCopying protocol (see the docs for what to add). Once that's added the code you posted above should work correctly.

You might want to consider using strings though over your own object for the key. The key is required to be a string if key-value coding is going to be used to access it at all. So using a string will make life easier if you can take advantage of key-value coding anywhere you're using the dictionary.

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