【问题标题】:Converting NSArray to NSString crashes?将 NSArray 转换为 NSString 崩溃?
【发布时间】:2013-01-31 20:44:07
【问题描述】:

试图获取一个标签来显示从一些 JSON 中提取的数据...

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSError *myError = nil;
        NSDictionary *res = [NSJSONSerialization JSONObjectWithData:jsonresponse         options:NSJSONReadingMutableLeaves  error:&myError];
        NSArray *results =  [res objectForKey:@"current_observation"];
        NSArray *cur = [results valueForKey:@"weather"];
        NSArray *tmp = [results valueForKey:@"temp_f"];
        NSString * tmpstring = [[tmp valueForKey:@"description"] componentsJoinedByString:@""];
        temp.text = tmpstring;
    }

当它运行该代码时,它会吐出这个...

2013-01-31 15:38:03.319 Places[4659:907] -[__NSCFString componentsJoinedByString:]: unrecognized selector sent to instance 0x5680d0
2013-01-31 15:38:03.321 Places[4659:907] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString componentsJoinedByString:]: unrecognized selector sent to instance 0x5680d0'
*** First throw call stack:
(0x32b3e3e7 0x3a82f963 0x32b41f31 0x32b4064d 0x32a98208 0x413b 0x3347a915 0x333ba769 0x333ba685 0x3281b64f 0x3281ad33 0x32843013 0x32a84acd 0x32843473 0x327a7461 0x32b138f7 0x32b1315d 0x32b11f2f 0x32a8523d 0x32a850c9 0x3666333b 0x349a12b9 0x20c9 0x2050)
libc++abi.dylib: terminate called throwing an exception
(lldb) 

有什么想法吗?

【问题讨论】:

  • 你确定[tmp valueForKey:@"description"]返回一个NSArray吗,它看起来好像在错误消息中返回一个NSString

标签: xcode json crash nsstring nsarray


【解决方案1】:

-description是继承自NSObject的方法,是NSObject协议的一部分;它返回一个带有对象描述的NSString *。所有类都可以覆盖它以返回任意 NSString。

-valueForKey: 将返回一个数组,其中包含在其所有对象上调用 -description 方法的结果。这似乎不是这里的情况,因为[tmp valueForKey:@"description"] 似乎返回一个NSString * 而不是一个数组。我猜tmp 不是数组,因此您的应用程序崩溃了。

如果不知道 JSON 数据实际上是什么,就不可能说出这里出了什么问题。请用一些示例数据更新您的问题。

【讨论】:

  • 它说“NSArray 没有可见的@interface 声明选择器'objectForKey:'”
  • 哦,好吧,我没有注意到您在 tmp 数组上调用 -valueForKey:。你认为这段代码应该做什么?我不明白。我假设您打算在字典中查询与 @"description" 键关联的对象。如果没问题,改成[[res objectForKey:@"description"] componentsJoinedByString:@""];
  • 我要做的就是将 *tmp 数组作为字符串显示在标签中。
  • tmp 数组包含一系列字符串?然后简单地做[tmp componentsJoinedByString:@""];
  • NSArray *tmp = [results valueForKey:@"temp_f"]; NSString *tmpstring = [tmp componentsJoinedByString:@""]; temp.text = tmpstring;
【解决方案2】:

描述为所有继承自 NSObject 的对象返回一个 NSString。 NSString 及其祖先都没有实现 componentsJoinedByString。 如果你想使用 componentsJoinedByString 你需要将它直接发送到一个 NSArray 或其他实现该方法的集合对象。 使用 Objective-C 中的嵌套消息传递,您需要确定返回的对象类是什么。如果您不确定,请将您的消息取消嵌套,这样您就会看到它是什么。 如果您在某些情况下无法确定,最好取消嵌套消息并使用诸如

之类的方法进行验证
if ([object respondsToSelector:@selector(someSelector:)]) {
     // do stuff here
} else {
     // some alternative
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多