objective-c - Objective C 中的 __NSSingleObjectArrayI 是什么意思?当我尝试阅读 Json

标签 objective-c json nsstring nsarray

我有这样的代码 Json 格式:

{
    "weather": [{
        "description": "clear sky",
        "icon": "01n"
    }],
    "base": "stations",
    "main": {
        "temp": 285.514
    },
    "clouds": {
        "all": 0
    },
    "dt": 1485792967,
    "id": 1907296
}

我想检索图标字符串 (01n)

并使用这段代码:

@property(nonatomic,strong) NSString *cityImageName;

self.cityImageName = [[dataJson valueForKey:@"weather"] valueForKey:@"icon"];

稍后当我检查变量打印时:

<__NSSingleObjectArrayI 0x604000009890>(
01n
)

最后我如何直接获取字符串?不像 __NSSingleObjectArrayI

最佳答案

您陷入了键值编码陷阱

valueForKey 有一个特殊的行为。应用于数组时,它始终返回给定键的所有值的数组。

除非您打算使用 KVC,否则永远不要使用 valueForKey。推荐的语法是 objectForKey 或 - 最好 - 键订阅,如果是数组索引订阅。

在这种情况下,您想要获取键 weather 数组中第一项的键 icon 的值。

self.cityImageName = dataJson[@"weather"][0][@"icon"];

但是如果数组不为空我会添加一个检查以避免超出范围的异常

NSArray *weather = dataJson[@"weather"];
if (weather && weather.count > 0) {
    self.cityImageName = weather[0][@"icon"];
}

关于objective-c - Objective C 中的 __NSSingleObjectArrayI 是什么意思?当我尝试阅读 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46939729/

相关文章:

objective-c - 为什么我的导航栏 Controller 不处理我的导航栏 View 上的 touchesEnded 事件?

php - json_encode() 拒绝两个 MySQL 列

c# - Windows Phone 的 Json 序列化

swift - 无法在 Label.text 中转换 NSString

objective-c - 在常量和非常量字符串之间交替时 NSString 的最佳分配

objective-c - 可变长度数组声明的解决方法不能有 'static' 错误

iOS VST 音频插件支持

php - 如何从php服务器获取json数据到android mobile

objective-c - 如何将 NSNumber 转换为 NSString

ios - 核心蓝牙 : scanForPeripheralsWithServices not working with service array