Stephen
Stephen

Reputation: 532

Key Value Coding: BOOL property evaluated as NSNumber of type "i", not "c"

When using NSObject valueForKey: for a property of type BOOL (Example code from someone else here), the NSNumber returned isn't @encode(BOOL) = "c" -- it's "i". Why?

Upvotes: 0

Views: 418

Answers (2)

Sushi Ninja
Sushi Ninja

Reputation: 1

This was the code from the linked website:

MyClass *c = [[MyClass alloc] init];
c.aaa = YES;

NSNumber *n = [c valueForKey:@"aaa"];

NSString *s = [NSString stringWithCString:[n objCType] encoding:NSUTF8StringEncoding];
NSLog(@"ObjC type - %@", s); // Prints 'i' instead of 'c'

It seems to be that you are asking for n's objCType when using [n objCType]; Since n is an NSNumber, it would follow that i is the result and not c.

Upvotes: -1

Lily Ballard
Lily Ballard

Reputation: 185663

BOOL isn't a fundamental type, it's a typedef for signed char. As such, at runtime it's impossible to tell if a property is a boolean or just an integral value. Therefore we can be certain that -valueForKey: is not using +numberWithBool: to wrap the value. So the question is, why isn't it using +numberWithChar:? Probably for simplicity sake. It would not surprise me if all signed integral values <= sizeof(int) are wrapped using +numberWithInt:. The real question is, why does it matter? If you ask the resulting NSNumber object for -boolValue you'll get the correct response.

Upvotes: 2

Related Questions