我正在尝试从字典中获取特定键的值,但我得到了一个[[__NSCFArray objectForKey:]:无法识别的选择器发送到实例”
-(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"]; } }
我NSLog我的头像字典,我的结果是:
( { "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"; } )
问题是您NSArray没有NSDictionary。的NSArray计数为1,并包含NSDictionary。
NSArray
NSDictionary
NSArray *wrapper= [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil]; NSDictionary *avatars = [wrapper objectAtIndex:0];
要遍历数组中的所有项目,请枚举数组。
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 }
注意:我也从-objectForKey:[]语法切换到了。我比较喜欢
-objectForKey: