NSValue 是如何发挥其魔力的?

发布于 2024-08-25 17:41:03 字数 428 浏览 4 评论 0 原文

我有一个 MVC 应用程序。该模型有一个属性,即 struct NSSize。它是可写的,如下所示:

- (void)setSize:(NSSize)aSize;

视图使用键值编码设置此NSSize。但是,您不能对结构进行键值编码,因此我将其包装在 NSValue 对象中,如下所示:

[theView setValue:[NSValue valueWithSize:mySize]
           forKey:@"theModel.size"];

据我了解,这应该不起作用,因为访问器需要一个结构而不是 <代码> NSValue 。但它工作得很好。神奇的是。

这怎么可能?

I have an MVC application. The model has a property that is a struct NSSize. It is writable like this:

- (void)setSize:(NSSize)aSize;

The view sets this NSSize using key-value-coding. However, you can not key-value-code a struct, so I wrapped it in an NSValue-object like this:

[theView setValue:[NSValue valueWithSize:mySize]
           forKey:@"theModel.size"];

To my understanding, this should not work since the accessor expects a struct and not an NSValue. But it works perfectly. Magically.

How is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

游魂 2024-09-01 17:41:03

向下滚动到“包装和展开结构”,但要点如下:

setValue:forKey: 确定指定键的适当访问器或实例变量所需的数据类型。如果数据类型不是对象,则使用适当的 -Value 方法从传递的对象中提取值。

顺便说一句,感谢您提出这个问题!这是可可中一直“有效”的东西之一,我从来没有认为它是如何完成的并不明显。

Scroll down to "Wrapping and Unwrapping Structs", but here's the gist:

setValue:forKey: determines the data type required by the appropriate accessor or instance variable for the specified key. If the data type is not an object, then the value is extracted from the passed object using the appropriate -<type>Value method.

Btw, thanks for asking this question! This is one of those cocoa things that has always "just worked" and I never considered that it wasn't obvious how it was accomplished.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文