【问题标题】:How to access NSMutableDictionary when the key looks like an int?当键看起来像一个 int 时如何访问 NSMutableDictionary?
【发布时间】:2020-11-03 16:15:34
【问题描述】:

我正在学习 Objective-c。

我试图通过使用数字作为键来获取这个NSMutableDictionary 的条目:

// [game analysisData] returns the Dictionary

NSMutableDictionary *data = [game analysisData];
NSLog(@"Data:\n%@", data);

// Try using "1" as the key.
id move = [data objectForKey:"1"];
NSLog(@"Move:\n%@", move);

但是输出不好:

move == (null).

所以我无法使用字符串"1" 访问它。使用 int 不起作用(编译错误)。

你知道我如何访问这个 NSMutableDictionary 的条目吗?

这是description 在 FLEXTool 中的样子:

【问题讨论】:

  • 似乎是NSNumber,但是有什么:for (id aKey in [data allKeys]) { NSLog(@"Key %@ is of class %@", aKey, NSStringFromClass([aKey class])); } 来检查:)

标签: objective-c nsdictionary


【解决方案1】:

您可以改用 NSNumber。你可以这样写:

NSNumber * key1 = @1;
NSNumber * key2 = @(1 + 1);
int intKey      = 3;
NSNumber * key3 = @(intKey);

你也可以用这样的字符串来做:

id move = [data objectForKey:@"1"]; // you forgot the @

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2011-07-04
    • 2010-10-17
    相关资源
    最近更新 更多