在objectiveC中使用int键映射

And*_*rew 2 objective-c mutable map nsdictionary

我需要将整数值映射到某种可变数组中的对象.什么是最好的方法来解决这个问题.我看到的唯一选择是使用objectiveC++ ...

std::map<int, id> theMap;  // if i can use id?
Run Code Online (Sandbox Code Playgroud)

或者将内注放入NSStringNSNumber用作钥匙NSMutableDictionary.

我在我的网络类中使用它,客户端将发送一些数据(密钥将在有效负载中).然后在读取时,将从数据包中提取密钥,然后将地图中的对象拉出以基于所接收的内容继续该程序.(我担心客户端无法接收有效负载或丢失有效负载.)

哪种方式最好/最快?

Mar*_*bri 5

最好的选择(如果你不想弄乱C++)是使用NSMutableDictionarywith NSNumbers作为键.使用新的文字语法更容易:

NSMutableDictionary *map = [NSMutableDictionary dictionary];
map[@1] = @"A value";
map[@578] = @"Another string";
int key = 310; // doesn't matter where this comes from
map[@(key)] = @"From a variable!";
Run Code Online (Sandbox Code Playgroud)