Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does NSValue do its magic?

Tags:

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?

like image 984
bastibe Avatar asked Mar 22 '10 20:03

bastibe


1 Answers

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.

like image 104
kubi Avatar answered Sep 27 '22 20:09

kubi