[__NSCFArray objectForKey:]: unrecognized selector sent to the instance

I try to get the value for a specific key from the dictionary, but I get "[__NSCFArray objectForKey:]: unrecognized selector sent to the 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:

 ( { "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"; } ) 
+6
source share
3 answers

The problem is that you have an NSArray not an NSDictionary . NSArray has a counter of 1 and contains an NSDictionary .

 NSArray *wrapper= [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil]; NSDictionary *avatars = [wrapper objectAtIndex:0]; 

To iterate over all the elements in an array, list 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 the syntax -objectForKey: to []. I like it better.

+19
source

The reason you see this is because avatars not an NSDictionary , but an NSArray .

I can say because:

  • the exception you get indicates that __NSCFArray (i.e. NSArray ) does not recognize the objectForKey: selector objectForKey:
  • when registering avatars it also prints a bracket ( . The array is registered as follows:

    (first element, second element, ...)

while the dictionary is registered this way:

 { firstKey = value, secondKey = value, … } 

You can fix it as follows:

 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 avatarImage .

+1
source

Try the following:

  NSMutableDictionary *dct =[avatars objectAtIndex:0]; NSDictionary *avatarimage = [dct objectForKey:@"- image"]; NSString *name = [dct objectForKey:@"name"]; 
-1
source

Source: https://habr.com/ru/post/946689/


All Articles