Reputation: 8497
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.
Upvotes: 1
Views: 1311
Reputation: 3861
If you are not able to use NSNumber to encapsulate the BOOL, nor NSNull, your next option is to create your own wrapper class:
@interface MyBoolean : NSObject
@property (nonatomic, assign) BOOL boolVal;
@end
Upvotes: 2
Reputation: 1344
To add booleans use [NSNumber numberWithBool:YES/NO] and for nil values use [NSNull null]. You should not care what the value was initially (boolean or number), the one who's using your JSON parser should know what to expect.
Upvotes: 5
Reputation: 6852
Your questions sounds a little confusing. What does this parameter, where you want to set this boolean, stand for? And why do you need to know if it was numeric or a boolean?
If you have such situations, it's always good to make your own model.
Upvotes: 0