将 NSNumber 0 添加到 NSDictionary

问题描述 投票:0回答:3

我需要根据 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
...

ios objective-c nsdictionary nsnumber zero
3个回答
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
投票

那又如何

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

1
投票
NSNumber* cityID;
NSNumber* zoneID;
if((cityID == nil)||(zoneID == nil))
{
    NSDictionary *cityDictionary = @{@"CityID": [NSNumber numberWithInt:0], @"CityZoneID": [NSNumber numberWithInt:0]};
}
© www.soinside.com 2019 - 2024. All rights reserved.