这个类不符合键值编码的要求,无法使用该键。

3

我感觉我可能漏掉了一些显而易见的东西,但是我刚开始学习objc,也许这只是我不知道的东西。

我在运行时得到了异常错误...

NSDictionaryI 0x9d384d0> setValue:forUndefinedKey:]: 这个类不支持键值编码(key value coding)的key overObject.'

在这段代码的第4行...

NSDictionary *tempDictionary = [[NSDictionary alloc] init];

    Boolean overObjectYES = NO;
    Boolean overObjectNo = NO;

    [tempDictionary setValue:[NSNumber numberWithBool:overObjectYES] forKey:@"overObject"];
3个回答

9

1
有点困惑,SetValue是为键设置对象的内容?而SetObject是为键设置实际对象本身? - Phil
2
@Phil 忽略setValue方法,它是一个更大更复杂的主题称为键值编码的一部分。使用setObject代替(这是NSMutableDictionary定义的一个方法)。 - borrrden
说实话,我不确定为什么会有两个信息——苹果的类参考资料表明setValue使用setObject,但如果传递了nil值,则会删除键-值对,而setObject则会引发一个NSInvalidArgumentException异常NSMutableDictionary Class Reference - Kendall Lister
2
@KendallLister 第一个是 NSKeyValueCoding 协议的一部分。任何 NSObject 都可以接受它,但某些类(例如 NSMutableDictionary)会覆盖其行为。 - borrrden

3

您是希望 tempDictionary 成为一个可变字典吗?如果是的话,请按以下方式声明:

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

1
使用NSMutableDictionaryNSDictionary不可编辑。
NSMutableDictionary *tempDictionary = [[NSMutableDictionary alloc] init];
Boolean overObjectYES = NO;
Boolean overObjectNo = NO;

[tempDictionary setValue:[NSNumber numberWithBool:overObjectYES] forKey:@"overObject"];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接