I'm attempting to serialize various objects by using Key-Value Coding to convert them to an NSDictionary, then JSONKit to serialize the NSDictionary to an NSString/NSData. I'm running into problems converting BOOL properties.
The KVC guidelines state that valueForKey:
will, for BOOL properties, create an NSNumber via [NSNumber numberWithBool:]
. JSONKit states that NSNumbers created via numberWithBool:
will be serialized to true/false. I've tested JSONKit's claim and it works. However, when I access a BOOL value with KVC, I get an object which does not look like it was created via numberWithBool:
. In particular, it does not evaluate equal to kCFBooleanTrue, which JSONKit uses as a marker for a boolean. The end result is that my BOOL properties are serialized to 0/1 instead of true/false, which is causing problems for the receiving API.
How do I determine if an NSNumber from KVC came from a BOOL property? Am I misreading Apple's documentation? Or is there some other way to get this serialization procedure to work?
Below is the test which is failing:
#import "JSONKit.h"
- (void) testCompareKVCBoolToNumberWithBool {
NSNumber *numberBool = [NSNumber numberWithBool:YES];
//This passes
STAssertTrue(numberBool == (id)kCFBooleanTrue, @"Number %@ should kCFBooleanTrue.", numberBool);
TestModel *model = [[TestModel alloc] init];
model.boolProperty = YES;
NSNumber *kvcBool = [model valueForKey:@"boolProperty"];
//This fails
STAssertTrue(kvcBool == (id)kCFBooleanTrue, @"Number %@ should be a kCFBooleanTrue.", kvcBool);
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
numberBool, @"numberBool",
kvcBool, @"kvcBool",
nil];
NSString *jsonString = [dict JSONString];
//This yields: jsonString: {"kvcBool":1,"numberBool":true}
NSLog(@"jsonString: %@", jsonString);
}
And here is the TestModel code:
@interface TestModel : NSObject
@property (assign) BOOL boolProperty;
@end
@implementation TestModel
@synthesize boolProperty = _boolProperty;
@end
Thanks!