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 "
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSDictionary *avatars = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(@"response:::%@", avatars);
if(avatars){
NSDictionary *avatarimage = [avatars objectForKey:@"- image"];
NSString *name = [avatars objectForKey:@"name"];
}
}
I NSLog my avatars Dictionary and my result is:
(
{
"created_at" = "2013-06-06T11:37:48Z";
id = 7;
image = {
thumb = {
url = "/uploads/avatar/image/7/thumb_304004-1920x1080.jpg";
};
url = "/uploads/avatar/image/7/304004-1920x1080.jpg";
};
name = Drogba;
"updated_at" = "2013-06-06T11:37:48Z";
}
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With