Comparison with null in object c

I'm starting to look for my code littered with:

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

Is there a shorter (characteristic) comparison for NULL?

Background: I use the SBJson library to parse a JSON string, and some of them often use null values ​​(by design).

+8
objective-c
source share
7 answers

Nothing is inlined, but it would be wise and simple to create the MYIsNull() function that would make the comparison you want. Just think about what you want to return in the absence of a key.

You can go the other way and convert -null to nil . For example, you can add a category to NSDictionary as follows:

 - (id)my_nonNullObjectForKey:(NSString *)key { id value = [self objectForKey:key]; if ([value isEqual:[NSNull null]) { return nil; } return value; } 
+7
source share

I would use

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

It seems to work because [NSNull null] actually an β€œobject”. Hope this helps!

+4
source share

No, you need to check NSNull . However, if you find that your code is littered with this, you can create #define for it.

Remember also that if p is nil or if p does not matter for someKey , then [p objectForKey@"somekey"] != [NSNull null] evaluates to YES .

So, you probably want something like this:

 #define IsTruthy(X) ( X && (X != [NSNull null]) ) 
+2
source share

Is there a shorter (characteristic) comparison for NULL?

[NSNull null] - 13 characters. You can say:

 NSNull.null // << 11 (id)kCFNull // << 11 

Or execute the function:

 IsNSNull([p objectForKey@"somekey"]) // << 10 in this case and requires no ==, != 

Or (cringes) use the category:

 [p objectForKey@"somekey"].mon_isNSNull // << 13 in this case, but requires no ==, != 

Just be careful what you call this category when dealing with nil receivers.

+1
source share

Since you are using SBJSON , you can easily change its code - you have a source.

I actually modified the SBJSON parser to skip the [NSNull null] values. They are not added to dictionaries, and when I call objectForKey: I never get [NSNull null] , I just get nil . Then, in most cases, I don’t even need to check if nil , since calling a method on nil usually gives the expected result.

0
source share

If you're just worried about the amount of time you type for input, consider the macros:

 #define ISNULL(key) [p objectForKey:key] == [NSNull null] 

then

 if (!ISNULL(@"somekey")) ... 
0
source share

Pretty sure you can just say

 if ([p objectForKey:@"somekey"]) { } 

I do not use NSNull, so I am not 100% sure, but I think that it checks as false and any other object tests as true.

-4
source share

All Articles