I am trying to get a value for a particular key from a dictionary but i get a \"[__NSCFArray objectForKey:]: unrecognized selector sent to instance \"
-(voi
The problem is you have a NSArray not an NSDictionary. The NSArray has a count of 1 and contains an NSDictionary.
NSArray *wrapper= [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *avatars = [wrapper objectAtIndex:0];
To loop through all items in the array, enumerate the array.
NSArray *avatars= [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
for (NSDictionary *avatar in avatars) {
NSDictionary *avatarimage = avatar[@"image"];
NSString *name = avatar[@"name"];
// THE REST OF YOUR CODE
}
NOTE: I also switched from -objectForKey: to [] syntax. I like that better.
Try this:
NSMutableDictionary *dct =[avatars objectAtIndex:0];
NSDictionary *avatarimage = [dct objectForKey:@"- image"];
NSString *name = [dct objectForKey:@"name"];
The reason you see that is because avatars is not a NSDictionary but is a NSArray instead.
I can tell because:
__NSCFArray (i.e. NSArray) doesn't recognize the objectForKey: selectorwhen logging avatars it prints also parenthesis (. An array is logged in this way:
( first element, second element, … )
while a dictionary gets logged in this way:
{
firstKey = value,
secondKey = value,
…
}
You can fix this in this way:
NSArray *avatars = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(@"response:::%@", avatars);
if(avatars){
NSDictionary *avatar = [avatars objectAtIndex:0]; // or avatars[0]
NSDictionary *avatarimage = [avatar objectForKey:@"- image"];
NSString *name = [avatar objectForKey:@"name"];
}
Also note that the key for the avatarImage is wrong.