将NSNumber 0添加到NSDictionary

时间:2013-09-18 08:02:22

标签: ios objective-c nsdictionary nsnumber zero

我需要根据ID创建一个用于搜索的字典,但如果没有选择ID,则必须存储0。

现在我可以这样做:

NSNumber* cityID;
NSNumber* zoneID; //These two do get value, just showing for their class
NSDictionary *cityDictionary = @{@"CityID": [NSNumber numberWithInt:(int)cityId], @"CityZoneID": [NSNumber numberWithInt:(int)zoneId]};

我觉得这样真的很乱。它会被转换为int,然后转回NSNumber ...

3 个答案:

答案 0 :(得分:2)

试试这个

// May be syntax change but you need to initialise with zero first
NSNumber* cityID = [NSNumber numberWithInt:0];
NSNumber* zoneID = [NSNumber numberWithInt:0]; //Init with Zero then you can added value for this if no value default will be 0
NSDictionary *cityDictionary = @{@"CityID": [NSNumber numberWithInt:(int)cityId], @"CityZoneID": [NSNumber numberWithInt:(int)zoneId]};

这可能会有所帮助

答案 1 :(得分:1)

NSNumber* cityID;
NSNumber* zoneID;
if((cityID == nil)||(zoneID == nil))
{
    NSDictionary *cityDictionary = @{@"CityID": [NSNumber numberWithInt:0], @"CityZoneID": [NSNumber numberWithInt:0]};
}

答案 2 :(得分:1)

怎么样?
NSDictionary *cityDictionary = @{
      @"CityID" :     (cityID == nil ? @0 : cityID),
      @"CityZoneID" : (zoneID == nil ? @0 : zoneID)
};