使用“生成的字符串” (stringWithFormat) 作为 NSDictionary 的键
我想做这样的事情:
#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)];
但我担心 stringWithFormat 方法返回具有相同值的 NSString 的不同实例,我的意思是有 2 个字符串:“0”和另一个值为“0”的实例。我想知道这是否是获取和设置字典中对象的安全方法。如果不是,什么其他方法可能是从整数“生成”密钥对象的最佳方法?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您正在做的事情是完全安全的,并且会按预期工作。字典的键在获取和设置时使用 isEqual 方法进行比较,该方法仅检查字符串的值,而不检查它们的地址。 “0”和“0”是相等的,无论它们是否是同一个实例。
您可以在 NSObject 协议参考。请注意,
==
和isEqual
不是同一件事(==
检查地址,isEqual
检查值)。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==
andisEqual
are not the same thing (==
checks addresses,isEqual
checks values).如果您期望所有这些都是数字,您应该考虑使用 NSNumber,但它也可以与 NSString 一起使用。 NSDictionary 键必须符合 NSCopying 协议,并且使用 isEqual: 选择器来比较键。
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.