Cocoa KVC:“类不符合键值编码”

发布于 2024-07-26 22:21:32 字数 495 浏览 9 评论 0原文

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

此行有效:

myObject.value = intValue;

这行不通:

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

并崩溃: 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[;” setValue:forUndefinedKey:]: 此类对于键 myObject.value 不符合键值编码。'

进一步,同一类的方法 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伤感在游骋 2024-08-02 22:21:32

您不能将键路径作为第二个参数传递给 -[NSObject setValue:forKey:]。 您想使用 setValue:forKeyPath: 代替:

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

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

You cannot pass a key path as the second argument to -[NSObject setValue:forKey:]. You want to use setValue:forKeyPath: instead:

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

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.

余生一个溪 2024-08-02 22:21:32

它告诉您这不是该对象的有效键,实际上也不是:“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.

鸩远一方 2024-08-02 22:21:32

我同意查克的观点。

我认为你需要这样做:

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

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

id myObject = [self objectForKey:@"myObject"];
[myObject setValue:[NSNumber numberWithInt:intValue] forKey:@"value"];

I agree with Chuck.

I think you need to do this instead:

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

or via each part of the key path like:

id myObject = [self objectForKey:@"myObject"];
[myObject setValue:[NSNumber numberWithInt:intValue] forKey:@"value"];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文