Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare to null in objective c

Tags:

objective-c

I am beginning to find my code littered with:

if([p objectForKey@"somekey"] != [NSNull null]) {

}

Is there shorter (character-wise) comparison for NULL?

Background: I am using the SBJson library to parse a JSON string and there are often null values (by design) for some of the keys.

like image 800
Adam Avatar asked Jun 07 '13 17:06

Adam


2 Answers

Nothing built-in, but it would be reasonable and simple to create a function MYIsNull() that would do the comparison you want. Just think through what you want to return in the case that the key is missing.

You may want to go the other way and transform -null into nil. For instance, you could add a category on NSDictionary like this:

- (id)my_nonNullObjectForKey:(NSString *)key {
   id value = [self objectForKey:key];
   if ([value isEqual:[NSNull null]) {
     return nil;
   }
   return value;
}
like image 99
Rob Napier Avatar answered Oct 09 '22 18:10

Rob Napier


I would use

if([[p objectForKey@"somekey"] isEqual:[NSNull null]] || ![p objectForKey@"somekey"]) {
    // NSNull or nil
} else {
    // Stuff exists...Hurray!
}

It seem to work since [NSNull null] is in fact an "object". Hope it helps!

like image 31
Groot Avatar answered Oct 09 '22 16:10

Groot