Cocoa KVC:“类不符合键值编码”
我正在尝试使用 KVC 更新一些属性。 属性已被合成。
此行有效:
myObject.value = intValue;
这行不通:
[self setValue:[NSNumber numberWithInt:intValue] forKey:@"myObject.value"];
并崩溃: 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[
进一步,同一类的方法 (awakeFromNib) 的其他实例对 setValue:forKey: 调用响应良好。 唯一的区别是这个特定实例是在 IB 中创建和连接的。
I'm trying to update some properties with KVC. The properties have been synthesized.
This line works:
myObject.value = intValue;
This doesn't work:
[self setValue:[NSNumber numberWithInt:intValue] forKey:@"myObject.value"];
And blows up with: Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MyViewController 0xd1cec0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myObject.value.'
Yet further up the method (awakeFromNib) other instances of the same class respond fine to setValue:forKey: calls. The only difference is this particular instance was created and wired up in IB.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能将键路径作为第二个参数传递给
-[NSObject setValue:forKey:]
。 您想使用setValue:forKeyPath:
代替:我的理解是
setValue:forKey:
是作为性能优化而提供的。 由于它不能采用密钥路径,因此它不必解析密钥字符串。You cannot pass a key path as the second argument to
-[NSObject setValue:forKey:]
. You want to usesetValue:forKeyPath:
instead:My understanding is that
setValue:forKey:
is provided as a performance optimization. Since it cannot take a key path, it doesn't have to parse the key string.它告诉您这不是该对象的有效键,实际上也不是:“myObject.value”是一个键路径,而不是单个键。
It's telling you that isn't a valid key for that object, and indeed it isn't: "myObject.value" is a keypath, not a single key.
我同意查克的观点。
我认为你需要这样做:
或者通过关键路径的每个部分,例如:
I agree with Chuck.
I think you need to do this instead:
or via each part of the key path like: