Monday, April 16, 2012

NSManagedObject NSNumber properties convert booleans to integers?

I am running into a problem with a NSManagedObject subclass where the value is set to boolean value, but the primitive type always seems to be an integer.



Here's a scenario that describes the problem:



If I have a method to check the primitive type of an NSNumber, like so:



- (BOOL) numberIsBool:(NSNumber*)numberToCheck {

const char *primitiveType = [numberToCheck objCType];

return (strcmp(primitiveType, @encode(BOOL)) == 0 );
}


And I execute the following code:



NSNumber *num = [NSNumber numberWithBool:YES];

BOOL isBool = [self numberIsBool:num];


As expected, primitiveType will be "c" and isBool will be YES.



However, if I take the NSManagedObject subclass:



@interface MyClass : NSManagedObject

@property (nonatomic, retain) NSNumber *myBoolValue;
...
@end


where myBoolValue is set to type Boolean in the model, and I execute the following code:



MyClass *myClass = ... (create from NSManagedObjectContext)

myClass.myBoolValue = [NSNumber numberWithBool:YES];

BOOL isBool = [self numberIsBool:num];


primitiveType will be set to "i" and isBool will be NO



Can anyone explain to me the reason for this or how I can get the myBoolValue property to honor the primitive type it was set with?



EDIT: So there is no confusion on what I am trying to accomplish - I am NOT trying to convert the NSNumber to a boolean. I already know how to do this with [myBoolValue boolValue].



EDIT #2 - More clarification: If I interrogate an NSManagedObject's properties. When the property is an NSNumber and it's value is 1 or 0, I need to take a different code path if it was intended to be a boolean than if it was intended to be an integer.





No comments:

Post a Comment