键值编码失败
Key value coding failure
所以我在这样的文件中有一些 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"];
编译器提示此键路径中没有符合键值编码的键。
烦人的是,这条线工作正常 returns 街道字符串
id value = [json valueForKeyPath:@"address.home.street"];
为什么我不能设置这样的值?
由于未捕获的异常 'NSUnknownKeyException' 而终止应用程序,原因:'[<__NSDictionaryI 0x1741bb580> setValue:forUndefinedKey:]:此 class 不符合键值编码用于键盘。'
阅读您的 JSON 时使用 NSJSONReadingMutableContainers。默认情况下,您的容器被读入为不可变容器。
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:nil];
所以我在这样的文件中有一些 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"];
编译器提示此键路径中没有符合键值编码的键。
烦人的是,这条线工作正常 returns 街道字符串
id value = [json valueForKeyPath:@"address.home.street"];
为什么我不能设置这样的值?
由于未捕获的异常 'NSUnknownKeyException' 而终止应用程序,原因:'[<__NSDictionaryI 0x1741bb580> setValue:forUndefinedKey:]:此 class 不符合键值编码用于键盘。'
阅读您的 JSON 时使用 NSJSONReadingMutableContainers。默认情况下,您的容器被读入为不可变容器。
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:nil];