[__NSCFArray objectForKey:]: unrecognized selector sent to instance

前端 未结 3 1302
执笔经年
执笔经年 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.

提交回复
热议问题