1

I need to create a dictionary with for a search, based on IDs, but if no ID gets selected, 0 has to be stored.

Now I can obviously do it like this:

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

I feel it's really messy like that. It gets cast to int, then turned back to NSNumber...

sKhan
  • 9,694
  • 16
  • 55
  • 53
Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76

3 Answers3

2

Try this

// 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]};

This may help

sKhan
  • 9,694
  • 16
  • 55
  • 53
1
NSNumber* cityID;
NSNumber* zoneID;
if((cityID == nil)||(zoneID == nil))
{
    NSDictionary *cityDictionary = @{@"CityID": [NSNumber numberWithInt:0], @"CityZoneID": [NSNumber numberWithInt:0]};
}
sKhan
  • 9,694
  • 16
  • 55
  • 53
karthika
  • 4,085
  • 3
  • 21
  • 23
  • If I'd go that route, I would need to make 4 if statements (both are good, A is good, B is good, neither are good). – Lord Zsolt Sep 18 '13 at 08:18
1

What about

NSDictionary *cityDictionary = @{
      @"CityID" :     (cityID == nil ? @0 : cityID),
      @"CityZoneID" : (zoneID == nil ? @0 : zoneID)
};
sKhan
  • 9,694
  • 16
  • 55
  • 53
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382