Boris Kuzevanov
Boris Kuzevanov

Reputation: 1302

iOS issue with loop in NSDictionary

I have array like this:

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

And i trying to get elements on loop like this discribed here

So there are my code:

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

and i have this error:

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) 

How i can to fix it? and Why i have error?

Whe i do debug i see that error in this line :

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

Upvotes: 0

Views: 59

Answers (2)

Ian MacDonald
Ian MacDonald

Reputation: 14030

It looks like self.codes is an array; you can't access that like a dictionary. The correct way to use your code is like this:

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

However, it really just looks like you're trying to access this:

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

Upvotes: 3

David Ansermot
David Ansermot

Reputation: 6112

The error is that you call a NSDictionary method on the NSArray method. self.codes is a NSArray, it needs to be a NSDictionary.

Upvotes: 0

Related Questions