[__NSCFArray objectForKey:]: unrecognized selector sent to instance

前端 未结 3 1303
执笔经年
执笔经年 2020-12-06 07:19

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         


        
相关标签:
3条回答
  • 2020-12-06 07:56

    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.

    0 讨论(0)
  • 2020-12-06 07:56

    Try this:

     NSMutableDictionary *dct =[avatars objectAtIndex:0];
    
     NSDictionary *avatarimage = [dct objectForKey:@"- image"];
    
     NSString *name = [dct objectForKey:@"name"];
    
    0 讨论(0)
  • 2020-12-06 08:03

    The reason you see that is because avatars is not a NSDictionary but is a NSArray instead.

    I can tell because:

    • the exception you get tells that __NSCFArray (i.e. NSArray) doesn't recognize the objectForKey: selector
    • when 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.

    0 讨论(0)
提交回复
热议问题