使用int作为NSDictionary键?

use*_*946 10 objective-c ios

我正在尝试访问我的字典对象.这是我的代码:

int tag = object.tag;
CGPoint point = [[self.dict objectForKey:tag] CGPointValue];
Run Code Online (Sandbox Code Playgroud)

问题是objectForKey应该采用Objective-C对象,而不是int.我尝试将标记包装到NSNumber中[NSNumber numberWithInt:tag]并将其传递给objectForKey:但是它返回一个空对象.

有任何想法吗?谢谢

bne*_*ely 14

如果您使用数字作为字典键的字符串,则应将其int转换为a NSStringNSNumber将其用作字典键.以下是如何为字符串执行此操作:

  NSString *key = [NSString stringWithFormat:@"%d", myInteger];
Run Code Online (Sandbox Code Playgroud)

正如@Hughes BR在评论中提到的那样,关键对象的要求是它必须符合NSCopying协议.

  • 你不需要使用字符串.一个`NSNumber`就足够了,可能更自然.`[NSNumber numberWithInteger:[object tag]]`会做的. (16认同)

Pet*_*mpf 5

我使用NSNumbers没有问题,但必须避免通常setObject: forKey:setValue: forKey:方法.这会产生警告.

但是,没有创建警告(并且代码按预期工作)

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
NSNumber *key = @1;
id *myObject  = [your code here];
myDict[key]   = myObject;
Run Code Online (Sandbox Code Playgroud)

检索很简单:

myObject = myDict[key];
Run Code Online (Sandbox Code Playgroud)