2

我正在尝试使用 KVC 更新一些属性。属性已合成。

这条线有效:

myObject.value = intValue;

这不起作用:

[self setValue:[NSNumber numberWithInt:intValue] forKey:@"myObject.value"];

并爆发: 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[<MyViewController 0xd1cec0> setValue:forUndefinedKey:]:此类与键 myObject.value 的键值编码不兼容。”

更进一步的方法 (awakeFromNib) 相同类的其他实例对 setValue:forKey: 调用响应良好。唯一的区别是这个特定的实例是在 IB 中创建和连接的。

4

3 回答 3

9

您不能将密钥路径作为第二个参数传递给-[NSObject setValue:forKey:]. 您想setValue:forKeyPath:改用:

[self setValue:[NSNumber numberWithInt:intValue] forKeyPath:@"myObject.value"];

我的理解是setValue:forKey:作为性能优化提供的。由于它不能采用密钥路径,因此不必解析密钥字符串。

于 2009-07-08T19:47:32.370 回答
7

它告诉您这不是该对象的有效键,实际上不是:“myObject.value”是键路径,而不是单个键。

于 2009-07-08T19:35:49.040 回答
1

我同意查克的观点。

我认为你需要这样做:

[self setValue:[NSNumber numberWithInt:intValue] forKeyPath:@"myObject.value"];

或通过关键路径的每个部分,例如:

id myObject = [self objectForKey:@"myObject"];
[myObject setValue:[NSNumber numberWithInt:intValue] forKey:@"value"];
于 2009-07-08T19:43:13.377 回答