Question

According to Apple's documentation Key-Value Coding Programming Guide you can call valueForKey: and setValue:forKey: on struct properties and they should be automatically wrapped in NSValue objects. I'm finding that when I make this call on an NSDecimal I get the following error:

-[NSInvocation getArgument:atIndex:]: struct with unknown contents found while getting argument at index -1

Can anyone shed light on how this is supposed to be done? Or is KVO broken for this case...

Was it helpful?

Solution

It seems that Key-Value Coding does not work with structs containing bit fields. So for this test class

typedef struct { int a; int b; } mystruct1;
typedef struct { int a:4; int b:4; } mystruct2;

@interface MyClass : NSObject
@property (nonatomic) mystruct1 s1;
@property (nonatomic) mystruct2 s2;  // struct with bit fields
@end

the following works, and returns a NSValue object:

MyClass *o = [[MyClass alloc] init];
mystruct1 s1 = { 4, 5 };
o.s1 = s1;
NSValue *v1 = [o valueForKey:@"s1"];

but the same code with the struct containing bit fields crashes with exactly the same message as in your question:

mystruct2 s2 = { 4, 5 };
o.s2 = s2;
NSValue *v2 = [o valueForKey:@"s2"]; // --> NSInvalidArgumentException

Since NSDecimal contains bit fields, this explains the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top