ios - 键值编码失败

标签 ios objective-c key-value-coding

所以我在这样的文件中有一些 json

{
"address": {
    "home": {
        "street": "A Street"
    }
}

我是这样拉出json串的

NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

我想使用键路径即时更改值,因此我需要制作结构的深层可变副本。所以我是这样做的

id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
data = [NSKeyedArchiver archivedDataWithRootObject:json];
json = [NSKeyedUnarchiver unarchiveObjectWithData:data];

使用断点我可以看到 json,一切看起来都很好。但是,我在这条线上崩溃了

[json setValue:@"Different Street" forKeyPath:@"address.home.street"];

编译器提示此键路径中没有符合键值编码的键。

恼人的是,这条线工作正常并返回街道字符串

id value = [json valueForKeyPath:@"address.home.street"];

为什么我不能设置这样的值?


由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[<__NSDictionaryI 0x1741bb580> setValue:forUndefinedKey:]:此类与键平移的键值编码不兼容。”

最佳答案

读取 JSON 时使用 NSJSONReadingMutableContainers。默认情况下,您的容器被读入为不可变容器。

id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:nil];

关于ios - 键值编码失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29236804/

相关文章:

java - 在不使用 java.util.Properties 的情况下读取文件并获取 key=value

ios - Firebase iOS - 在数据库中搜索具有特定 ID 值的字典

ios - Swift SVG 填充颜色到 SVG 图像

objective-c - 使用-setValue :forKey: vs "object.var = ..."

ios - 匹配 NSDate 中任何一年的给定日期和月份?

objective-c - 将 NSSet 中的对象与 NSArray 中的对象进行比较

objective-c - KVC 与 NSArrays 的 NSArrays

ios - UIPageviewController 使用 Storyboard 崩溃

ios - 如何在 TableView 单元格之间进行分隔

objective-c - iOS 核心动画加速