【问题标题】:NSDictionary not key value coding-compliant for the key TestNSDictionary 与键 Test 的键值编码不兼容
【发布时间】:2014-03-26 12:23:12
【问题描述】:

我正在尝试以一种可以在其中存储NSArrays 的方式使用NSDictionary,但我什至无法让它用于字符串。

_times = [[NSDictionary alloc] init];
NSString *test = @"Test";
[_times setValue:@"testing" forKey:test];
NSLog(@"%@",[_times objectForKey:test]);

对于上面的代码,我收到错误消息
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0x8b86540> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Test.'

为什么NSString * 不能用作密钥?事实上,这正是该方法所要求的。

【问题讨论】:

  • 把我的 5 美分留在这里,以防有人在使用 setValue:forKeyPath: 时收到此错误,您应该知道: - 即使您的顶级字典对象可能是可变的 (NSMutableDictionary),- 那个您尝试通过 keyPath 访问可能仍然是不可变的 (NSDictionary),这确实会导致上述错误。

标签: ios objective-c nsstring nsdictionary


【解决方案1】:

NSDictionary 是不可变的,因此您无法为其设置值。
使用NSMutableDictionary

NSMutableDictionary *times = [[NSMutableDictionary alloc] init];

我在这里包括@Martin 的评论

另外:使用setObject:forKey 设置字典值。 setValue:forKey 仅用于“键值编码”魔法setObject:forKey 如果应用于不可变字典,也会给出更好的错误消息。

【讨论】:

  • @Inbl:另外:使用setObject:forKey 设置字典值。 setValue:forKey 仅用于“键值编码魔法”。 setObject:forKey 如果应用于不可变字典,也会给出更好的错误消息。
  • @Inbl 这当然是正确的,尽管这并不能完全解决最初的问题。当您使用字典时,请确保您调用的是-setObject:forKey:-setValue:forKey: 保留用于键值编码,使用前者会导致编译时错误而不是运行时错误。
【解决方案2】:

此外,对于字典,KVC 是一种设置键/值对的低效方式。最好使用 NSMutableDictionary 方法 setObject:forKey:

【讨论】:

    猜你喜欢
    • 2013-10-11
    • 2011-03-26
    • 2019-08-20
    • 2013-05-23
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多