为什么我得到"[__NSArrayI allKeys]:无法识别的选择器发送到实例"/为什么NSDictionary转换?

Dou*_*ith 2 api objective-c nsdictionary nsarray ios

看起来这个[__NSArrayI allKeys]: unrecognized selector sent to instance错误,它似乎发生在你发送NSArray的allKeys消息时NSDictionary,但是在这种情况下我很清楚地将它发送到NSDictionary.

这是我与Pocket API接口时使用的代码:

        NSDictionary *articles = [response objectForKey:@"list"];

        // Create an array we can use to sort the keys (and thus the articles) in order of when they were added
        NSMutableArray *allKeys = [[articles allKeys] mutableCopy];
Run Code Online (Sandbox Code Playgroud)

最后一行导致错误.但是articles非常明确地宣称是NSDictionary?为什么不喜欢它?

奇怪的是,如果我在运行时检查它,它说它是一个NSArray!为什么会改变?

(lldb) po articles
$5 = 0x082103e0 <__NSArrayI 0x82103e0>(

)

(lldb) po [articles class]
$6 = 0x01b83b8c __NSArrayI
(lldb) 
Run Code Online (Sandbox Code Playgroud)

Wai*_*ain 6

它可能在您的代码中声明为字典,但这不会使它成为字典.它确实是一个数组,这就是你获得异常的原因.检查一下response你知道你应该期待什么.

您的代码编译是因为编译器不知道它将成为一个数组并且它相信它将是一个字典.它这样做是因为objectForKey:返回id.