【问题标题】:[__NSCFArray objectForKey:]: unrecognized selector sent to instance[__NSCFArray objectForKey:]:发送到实例的无法识别的选择器
【发布时间】:2013-06-06 13:20:56
【问题描述】:

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

【问题讨论】:

    标签: json cocoa-touch


    【解决方案1】:

    问题是你有一个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: 切换到 [] 语法。我更喜欢这样。

    【讨论】:

    • 是的,这行得通,但如果我有多个对象怎么办?我是否从NSArray 获取对象数量然后循环它?另外这是NSArray 而不是NSDictionary
    • 奇怪,我认为我的 plist 应该返回一个数组,但你说得对,我需要一个包装数组。谢谢!
    【解决方案2】:

    您看到的原因是因为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 的密钥是错误的。

    【讨论】:

    • 谢谢。所以这是一个包含 NSDictionary 的数组?在您的回答中,您使用的密钥与我 - image 使用的密钥相同,我想这是一个错误?
    【解决方案3】:

    试试这个:

     NSMutableDictionary *dct =[avatars objectAtIndex:0];
    
     NSDictionary *avatarimage = [dct objectForKey:@"- image"];
    
     NSString *name = [dct objectForKey:@"name"];
    

    【讨论】:

    • 我收到此代码的错误`no visible interface for a
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多