1

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!

jagill
  • 692
  • 4
  • 12

1 Answers1

0

You may want to checkout my implementation which does this automatically - https://github.com/QBurst/KVCObjectSerializer

Mahadevan Sreenivasan
  • 1,144
  • 1
  • 9
  • 26
  • This has the same problem that my implementation has, which is that a `BOOL` is converted into `0` or `1`, not `true` or `false`. Check out https://gist.github.com/3762811 for more details. – jagill Sep 21 '12 at 17:32
  • Thanks for the feedback. Will look into the issue and your implementation. :) – Mahadevan Sreenivasan Sep 23 '12 at 03:37