views:

304

answers:

2

Is there a way I can check to see if a value is NULL/Nil before assigning it to a BOOL?

For example, I have a value in a NSDictionary that can be either TRUE/FALSE/NULL

mySTUser.current_user_following = [[results objectForKey:@"current_user_following"]boolValue];

When the value is NULL I get the following error

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSNull boolValue]: unrecognized selector sent to instance

I would like to be able to handle the NULL case.

+4  A: 

You can test first and assign then conditionally, e.g. something like the following:

if (NSValue* val = [results objectForKey:@"current_user_following"]) {
    mySTUser.current_user_following = [val boolValue];
}

This:

  • avoids calling objectForKey: twice by storing the result in a variable
  • limits the scope of the variable to the if statement
  • works because nil is is equivalent to 0
  • thus only executes the assignment statement if val is not nil

To additionally check for the value being NSNull you'd have to add another test as given by ChristopheD, but i question wether NSNull is really needed here - YES/NO should be sufficient for a description like "is following".
If you have no useful value for a key, you could simply remove it from the dictionary or not insert it in the first place.

Georg Fritzsche
did you mean [val boolValue] rather than [obj boolValue]?
progrmr
@kk6yb: Oops, thanks.
Georg Fritzsche
+3  A: 

You should check for [NSNull null]:

id vUser = [results objectForKey:@"current_user_following"];

if (vUser != [NSNull null]) {
    // do stuff...
}
else {
    // handle the case appropriately...
}
ChristopheD
Why call `objectForKey:` twice for the same key?
Georg Fritzsche
@gf: good point, updated my post a little ;-)
ChristopheD
You should also check for nil being returned i.e. no entry for the key exists in the dictionary.
JeremyP