【问题标题】:Key value coding failure键值编码失败
【发布时间】:2015-03-24 15:35:12
【问题描述】:

所以我在这样的文件中有一些 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> setValue:forUndefinedKey:]:此类不符合键值编码的键值。”

【问题讨论】:

  • 请准确粘贴编译器/崩溃日志所说的内容。
  • 是什么让你认为 dict 是可变的?只需一个简单的NSLog(@"%@", [json class]); 就会显示 => __NSDictionaryI
  • 由于未捕获的异常'NSInternalInconsistencyException',这将返回类似终止应用程序的错误,原因:'-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
  • 但我没有收到该错误
  • @robdashnash 不要将setObject:forKey:setValue:forKey: 混淆(一个是NSMutableDictionary 的方法,而另一个是NSKeyValueCoding 协议的方法)......它们会产生不同的错误。字典是不可变的,这就是问题所在......

标签: ios objective-c key-value-coding


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-25
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 2017-10-20
    • 2021-10-27
    相关资源
    最近更新 更多