Taking Notes

cause i'll forget

Comparing to NSNull

Checks to NSNull come up a lot when dealing with things like parsing JSON and while it’s mostly just ==, there are some options.

The officially sanctioned method is NSNull sample code, but this will generate a warning in clang (BOOO HISSSS).

So here are the options as I see them:

- (void)someMethod
{
    NSString *aString = @"loremipsum";
    
    // This will complain: "Comparison of distinct pointer types ('NSString *' and 'NSNull *')"
    if (aString != [NSNull null])
    {
        
    }
    
    // This works (at least for strings), but isEqual: does different things 
    // for different classes, so it's not ideal
    if ([aString isEqual:[NSNull null]]) 
    {
        
    }
    
    // If you cast it to the class you're comparing against
    // then you're good to go
    if (aString != (NSString *)[NSNull null])
    {
        
    }
    
    // But we can also just cast it to id and
    // that works generically
    if (aString != (id)[NSNull null])
    {
        
    }
    
    // The thing that would be really cool,
    // would be [NSNull null] returning
    // id (like in the sample category below).
    // Wouldn't count on that one though.
    if (aString != [NSNull idNull])
    {
        
    }
}
@interface NSNull (idNull)
+ (id)idNull;
@end
@implementation NSNull (idNull)
+ (id)idNull { return [NSNull null]; }
@end

Casting to (id) seems like the simplest way to handle this one, so that’s the one I’m using right now.

Update:

One of my coworkers, @pgor, pointed out that he uses NSNull’s isEqual, which seems like a sensible enough thing to do. (I’m guessing Apple isn’t going to toss anything to screwy into an isEqual on an object that’s basically single purpose.)

if ([[NSNull null] isEqual:aString]) 
{
        
}

Also forgot to mention in the original post: it’s worth filing a bug against the documentation on NSNull to see what Apple’s official position is in this post static humiliator world we inhabit.

Radar