在NSDictionary中使用循环的iOS问题

时间:2014-10-22 13:50:42

标签: ios objective-c

我有这样的数组:

(
        {
        code = "+39";
        country = "Italy (+39)";
    },
        {
        code = "+93";
        country = "Afghanistan(+93)";
    },
)

我试图在循环中获取元素,如此描述here

所以有我的代码:

int i = 0;
for (id key in self.codes) {
    NSDictionary *value = [self.codes objectForKey:key];
    if(row == i)
    {
        return [value objectForKey:@"country"];
    }
    i++;
}

我有这个错误:

2014-10-22 15:49:56.791 Surfree[1097:60b] -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x15387e00
2014-10-22 15:49:56.793 Surfree[1097:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x15387e00'
*** First throw call stack:
(0x2e385ecb 0x38b20ce7 0x2e3897f7 0x2e3880f7 0x2e2d7058 0xe51af 0x30e27bf9 0x30e2ae81 0x3112984b 0x30cea179 0x30c913db 0x30cd5c8f 0x3107ec81 0x31128d7b 0x30e29bcf 0x30e29a85 0x30e2a7eb 0x30e27159 0x30e2724f 0x30bb6d17 0x30bb6a85 0x30bb63ed 0x2ececd33 0x30bb6271 0x30bc2ffd 0x30bc2a73 0x30d8c165 0x30bb6d17 0x30bb6a85 0x30bb63ed 0x2ececd33 0x30bb6271 0x30bc2ffd 0x30bc2a73 0x30d8b979 0x30bc90b5 0x30d8b1cd 0x30d483b1 0x30c6546f 0x30c65279 0x30c65211 0x30bb72e5 0x3083331b 0x3082eb3f 0x3082e9d1 0x3082e3e5 0x3082e1f7 0x30bba99f 0x2e350faf 0x2e350477 0x2e34ec67 0x2e2b9729 0x2e2b950b 0x332286d3 0x30c1a871 0xe6bd9 0x3901eab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

我该如何解决?为什么我有错误?

我在调试时看到这行中的错误:

NSDictionary *value = [self.codes objectForKey:key];

2 个答案:

答案 0 :(得分:3)

看起来self.codes是一个数组;你不能像字典那样访问它。使用代码的正确方法如下:

int i = 0;
for (NSDictionary *value in self.codes) {
  if(row == i)
  {
    return [value objectForKey:@"country"];
  }
  i++;
}

然而,看起来你真的只是试图访问它:

self.codes[row][@"country"]

答案 1 :(得分:0)

错误是您在NSDictionary方法上调用NSArray方法。 self.codes是NSArray,它必须是NSDictionary