开发者

Using "generated strings" (stringWithFormat) as keys for NSDictionary

I would like to do something like this:

#define GETKEY (a) ([NSString stringWithFormat:@"%d",a])

NSMutableDictionary *mutableDictionay=[NSMutableDictionary dictionary];
//population of dictionary
[mutableDictionary setObject:anObject forKey:GETKEY(someIntValue)];
//... then retrive the object
[mutableDictionary getObjectForKey:GETKEY(someIntValue)];

But 开发者_JAVA技巧I'm concerned the stringWithFormat method returns a different instance of NSString with the same value, I mean like having, 2 strings: "0" and another instance with value "0". I would like to know if this is a safe way to get and set the objects in the dictionary. If not, what other way could be the best way to "generate" a key object from an integer?


Yes, what you're doing is perfectly safe, and will work as expected. The keys of a dictionary when getting and setting are compared using the isEqual method, which only checks the values of the strings, and not their addresses. "0" and "0" are equal, regardless of whether they are the same instance or not.

You can read more about the isEqual documentation in the NSObject Protocol Reference. Just be aware that == and isEqual are not the same thing (== checks addresses, isEqual checks values).


You should consider using NSNumber if expect all of them to be numbers but it will work with NSString also. The NSDictionary keys must conform to NSCopying protocol and keys are compared using the isEqual: selector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜