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

时间:2014-07-04 00:25:24

标签: ios objective-c json xcode5

我正在创建扫描条形码的应用程序,并从Web服务中检索信息。

我有一个Web服务设置,它以JSON格式返回值。记录JSON中的所有值时,一切正常。问题是尝试记录单个值时。应用程序崩溃了,我看到了:

  • 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [__ NSCFString objectForKey:]:无法识别的选择器发送到实例0x170224f40'*

做了大量的研究我在这里遇到了几个与我遇到的问题类似的问题。有些人帮助我朝着正确的方向前进。我仍然无法找到解决方案的原因。

以下是应用崩溃的代码:

//NSDisctionary
res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

for(id key in res) {

    id value = [res objectForKey:key];

    NSString *keyAsString = (NSString *)key;
    NSString *valueAsString = (NSString *)value;

    NSLog(@"key: %@", keyAsString);
    NSLog(@"value: %@", valueAsString);
}

//NSMutableArray
results = [res objectForKey:@"error"];

//result is a dictionary
for (result in results) {

    message = [result objectForKey:@"message"];

    NSLog(@"Code Above: %@", message);

}

应用程序在第二个for循环中崩溃:

message = [result objectForKey:@"message"];

这就是我的JSON的样子:

{
    "error": {
        "code": 1,
        "message": "No UPC Code for this scan"
    },
    "data": null
}

有人能够看到我在哪里错了吗?真正赞赏正确方向的暗示。

非常感谢。

2 个答案:

答案 0 :(得分:3)

//NSMutableArray
results = [res objectForKey:@"error"];

//result is a dictionary
for (result in results) {

    message = [result objectForKey:@"message"];

    NSLog(@"Code Above: %@", message);

}

当您快速枚举字典时,您可以快速枚举其。因此,resultresults中的关键。因此[result objectForKey:@"message"]正在尝试将字符串视为字典。

您可能打算改为输入[[results objectForKey:result] objectForKey:@"message"]。虽然我将其写为results[result][@"message"]而已。

另外,为什么results被定义为可变数组?基于JSON,它是一本字典。编译器无法真正了解它,因此它相信它是一个数组,这意味着在编译时检查NSArray类型的objectForKey:类型。 results应该是字典。

另见:

答案 1 :(得分:0)

results = [res objectForKey:@"error"]; // results is NSDictionary with keys "code" and "message"
message = [results objectForKey:@"message"]; // No UPC Code for this scan
NSLog(@"Code Above: %@", message);