Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[__NSCFArray objectForKey:]: unrecognized selector sent to instance

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";
}
)
like image 695
nupac Avatar asked Jun 06 '13 13:06

nupac


1 Answers

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.

like image 68
Jeffery Thomas Avatar answered Dec 25 '22 03:12

Jeffery Thomas