首先,让我向您展示这段代码:

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类型的未捕获异常终止

最佳答案

您应该使用-objectForKey:而不是-valueForKey:
参见:Difference between objectForKey and valueForKey?

关于ios - 为什么不可能将NSDictionary valueForKey方法强制转换为NSString?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37836299/

10-10 21:12