Similar to a Javascript-Object I need to store boolean values and nil values in an objective-C NSDictionary. (This problem did raise when I tried to write an universal JSON-Parser) (Yes, I know there are some good ready-to-use-parsers out there, but I wanted to try to write my own.)
This is an example for what I want to do:
NSString* str = @"a string";
NSNumber* num = @123.456;
NSArray* arr = @[@"abc",@99];
boolean boo = true;
id obj = nil;
NSDictionary* dict = @{
@"key1" : str,
@"key2" : num,
@"key3" : arr,
@"key4" : boo, //will not work since boo is not an object
@"key5" : obj //will not work since obj is nil
};
//later in the same piece of code:
dict = @{
@"key1" : str,
@"key2" : num,
@"key3" : arr,
@"key4" : @1, //Here we have the NSNumber 1 assigned to key4
//(which is not the boolean value true)
@"key5" : @"" //an empty NSString-Object (which is not nil)
};
boolean
One solution could be, that I do this:
...
@"key4" : [NSNumber numberWithBool:boo];
...
But if boo is true the result would be exactly the same as
...
@"key4" : @1;
...
If it was false, it would be identic to
...
@"key4" : @0;
...
But I need to know if the original value was a boolean value or a numeric number.
nil vs. placeholder-object
Instead of asigning nil as a value to the dictionary I could use a placeholder like an empty string (@””), a certain number (-1) or something else. But later, I have no chance to find out, if I did store the placeholder because I wanted to store nil, or if I did store a valid value that by accident is identic to my placeholder.
If you are not able to use NSNumber to encapsulate the BOOL, nor NSNull, your next option is to create your own wrapper class: