【发布时间】:2016-06-15 13:04:22
【问题描述】:
首先,让我给你看一段代码:
NSURL *url = [NSURL URLWithString:@"http://www....../struct1.js"];
//create a NSData file from url.
NSData *myData = [NSData dataWithContentsOfURL:url];
NSError *theError = nil;
//some framework
NSDictionary *dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:myData error:&theError];
NSString * products;
for(id key in dict){
NSLog(@"key: %@, value: %@",key,[dict objectForKey:key]);
if([key isEqualToString:@"product_reviews"]){
products = (NSString *)[dict valueForKey:key];
break;
}
}
//gives an error at the execution, why?
NSLog(@"products : %@",[NSString stringWithString:products]);
我在执行时遇到错误,例如 products 不是 NSString,不是吗?为什么我不能投?
这是错误:
0x00e0eb2c __84-[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:]_block_invoke3246 + 68
19 UIKit 0x00de5b8a -[UIApplication workspaceDidEndTransaction:] + 163
2123
31 UIKit 0x00de52da -[UIApplication _run] + 540
....... .....
32 UIKit 0x00deaeb9 UIApplicationMain + 160
33 App1 0x000416ca main + 138
34 libdyld.dylib 0x03156a25 start + 1
) libc++abi.dylib:以 NSException 类型的未捕获异常终止
【问题讨论】:
-
您可以添加数据样本吗?你确定 products 不是 nil 在 NSLog 行吗?
-
究竟是什么错误?编译还是运行时?显示堆栈跟踪和您正在生成的日志输出
-
在您的
if测试之后:NSLog(@"Value class: %@" [dict[key] class])显示了什么? -
不要使用 valueForKey:。使用 objectForKey:除非您清楚地了解需要使用键值编码。
-
是的,您对
(NSString *)anNSArrayObject所做的事情,在您的情况下,anNSArrayObject是dict[key]。所以stringWithString:anNSArrayObject会导致崩溃,我猜控制台中有一个Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ZzZ selectorName:]: unrecognized selector sent to instance"你没有给出的地方。
标签: ios objective-c nsdictionary