NSNumber 作为 NSDictionary 的键 [英] NSNumber as key for NSDictionary

查看:101
本文介绍了NSNumber 作为 NSDictionary 的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 NSDictionary 中的键是如何工作的.通常,我会使用 NSString 作为键,例如:

I was wondering how keys work in a NSDictionary. Usually, I will use a NSString as a key for example:

NSString *stringKey = @"stringKey";
[mydict objectForKey:stringKey];

如果我想使用 NSNumber 怎么办:

What if I wanted to use a NSNumber:

NSNumber *numberKey = [NSNumber numberWithInt:3];
[mydict objectForKey:numberKey];

字典会去寻找数字为 3 的键吗?还是只是比较 numberKey 的地址?

Does the dictionary go look for the key with number 3? or would it just compare the address of the numberKey?

推荐答案

两个键相等当且仅当 [key1 isEqual:key2].某些类可能会使用 return self == other;-[NSObject isEqual:] 实现,但它对于类很常见(例如 NSStringcode>、NSNumber 等)来覆盖它以进行更多特定于上下文的比较.

Two keys are equal if and only if [key1 isEqual:key2]. Some classes may go with the -[NSObject isEqual:] implementation of return self == other;, but it's quite common for classes (such as NSString, NSNumber, etc) to override it to do more context-specific comparison.

这篇关于NSNumber 作为 NSDictionary 的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆