DevPrep

All topics › Objective-C

nil, Nil, NULL, NSNull

Middle PRO

Four kinds of "nothing"

The first three are null pointers that differ only in type and usage convention; the fourth is a real object.

#import <Foundation/Foundation.h>

static void demo(void) {
    id obj = nil;
    Class cls = Nil;
    char *cstr = NULL;
    NSArray *row = @[@"Ann", [NSNull null], @42];
    for (id value in row) {
        if (value == [NSNull null]) {   // singleton — pointer comparison
            NSLog(@"missing");
        }
    }
    NSLog(@"%@ %@ %s", obj, cls, cstr ? cstr : "");
}

Trap: [NSNull null] is a live object, and [[NSNull null] length] crashes with "unrecognized selector" rather than returning 0 as it would with nil. So values from JSON must be checked for NSNull, not nil.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store