Tuesday, July 13, 2010

How to check if bool is null.


A handy way to check if a stored bool value does not exist.  originally from http://stackoverflow.com/questions/2760112/how-to-check-if-a-bool-is-null
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.

No comments:

Post a Comment