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.
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;
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With