如何在NSDictionary中存储boolean和nil值?

时间:2012-10-25 15:48:51

标签: objective-c

与Javascript-Object类似,我需要在objective-C NSDictionary中存储布尔值和nil值。 (当我尝试编写一个通用的JSON-Parser时,这个问题确实提出了)(是的,我知道那里有一些很好的即用型解析器,但我想尝试编写自己的解析器。)

这是我想要做的一个例子:

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)
};

布尔
一个解决方案可能是,我这样做:

    ...
    @"key4" : [NSNumber numberWithBool:boo];
    ...

但如果boo为true,结果将与

完全相同
    ...
    @"key4" : @1;
    ...

如果它是假的,那么

是明智的
    ...
    @"key4" : @0;
    ...

但我需要知道原始值是布尔值还是数字。

nil vs.占位符对象
我可以使用占位符,如空字符串(@“”),特定数字(-1)或其他内容,而不是将nil作为值添加到字典中。但是后来,我没有机会发现,如果我确实存储了占位符,因为我想存储nil,或者我确实存储了一个有意义的值,这对于我的占位符来说是偶然的。

3 个答案:

答案 0 :(得分:5)

要添加布尔值,请使用[NSNumber numberWithBool:YES / NO],对于nil值,使用[NSNull null]。你不应该关心最初的值(布尔值或数字),使用你的JSON解析器的人应该知道会发生什么。

答案 1 :(得分:2)

如果您无法使用NSNumber来封装BOOL,也不能使用NSNull,那么您的下一个选择是创建自己的包装类:

@interface MyBoolean : NSObject
@property (nonatomic, assign) BOOL boolVal;
@end

答案 2 :(得分:0)

你的问题听起来有些混乱。 这个参数,你想设置这个布尔值,代表什么? 为什么你需要知道它是数字还是布尔值?

如果您遇到这种情况,那么制作自己的模型总是好的。