[__NSCFArray objectForKey:]:无法识别的选择器发送到实例

时间:2013-06-06 13:20:57

标签: json cocoa-touch

我试图从字典中获取特定键的值,但我得到一个“[__ 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";
}
)

3 个答案:

答案 0 :(得分:19)

问题是您有NSArray而不是NSDictionaryNSArray的计数为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:切换到[]语法。我更喜欢那样。

答案 1 :(得分:1)

您认为这是因为avatars不是NSDictionary,而是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的密钥错误。

答案 2 :(得分:-1)

试试这个:

 NSMutableDictionary *dct =[avatars objectAtIndex:0];

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

 NSString *name = [dct objectForKey:@"name"];