7

我试图从字典中获取特定键的值,但我得到一个“[__NSCFArray objectForKey:]: unrecognized selector sent to 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"];
}
}

我 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";
}
)
4

3 回答 3

20

问题是你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:到 [] 语法。我更喜欢那个。

于 2013-06-06T13:27:03.497 回答
1

你看到的原因是因为avatars不是a NSDictionary,而是a NSArray

我可以说是因为:

  • 您得到的异常表明__NSCFArray(即NSArray)无法识别objectForKey:选择器
  • 记录时avatars它也会打印括号(。数组以这种方式记录:

    (第一个元素,第二个元素,……)

当字典以这种方式记录时:

{
  firstKey = value,
  secondKey = value,
  …
}

您可以通过以下方式解决此问题:

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"];
}

另请注意,密钥avatarImage是错误的。

于 2013-06-06T13:29:48.373 回答
-1

尝试这个:

 NSMutableDictionary *dct =[avatars objectAtIndex:0];

 NSDictionary *avatarimage = [dct objectForKey:@"- image"];

 NSString *name = [dct objectForKey:@"name"];
于 2013-06-06T13:25:15.400 回答