所以我在这样的文件中有一些 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/