我试图从字典中获取特定键的值,但我得到一个“[__ 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 *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:切换到[]语法.我更喜欢这样.