20

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
bastibe
  • 16,551
  • 28
  • 95
  • 126
  • 1
    +1 this is a great question, because key-value coding is one of the truly *awesome* things about the Cocoa frameworks. Also, +1 for the "magic" tag! – Dave DeLong Mar 22 '10 at 21:36

1 Answers1

12

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.

kubi
  • 48,104
  • 19
  • 94
  • 118