objective-c - NSValue 是如何发挥它的魔力的?

标签 objective-c struct key-value-coding

我有一个 MVC 应用程序。该模型有一个属性,它是一个结构 NSSize。它可以这样写:

- (void)setSize:(NSSize)aSize;

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

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

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

这怎么可能?

最佳答案

向下滚动到“Wrapping and Unwrapping Structs”,但这里是要点:

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.

顺便说一句,感谢您提出这个问题!这是 cocoa 一直“有效”的东西之一,我从没想过它是如何完成的。

关于objective-c - NSValue 是如何发挥它的魔力的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2495484/

相关文章:

ios - 如何 Bundle.preferredLocalizations(来自 :) works

objective-c - Adobe Acrobat 干扰使用 WebView 显示的 PDF 文件

objective-c - 将字符串添加到数组

c - 通过地址将结构传递给函数与 C 中的指针

c - 使用内联汇编将 int 保存在来自结构指针的函数变量中

objective-c - NSTableView 内容未正确刷新

c - 理解结构函数 *adds 和 rel_list

xcode - Interface Builder 的用户定义的运行时属性不接受 float ?

cocoa - mutableArrayValueForKey 的 KVC 搜索模式是什么?

iphone - 为什么在访问对象属性时应该使用 KVC 而不是简单的点语法?