nil, Nil, NULL, NSNull
Four kinds of "nothing"
The first three are null pointers that differ only in type and usage convention; the fourth is a real object.
nil—(id)0, the null pointer to an object. Messagingnilis safe and returns zero.Nil—(Class)0, the null pointer to a class (Class cls = Nil).NULL—((void *)0), the null C pointer:char *,int *, blocks in C APIs, anNSError **argument (when you do not need the error). Numerically all three are zero and the compiler does not distinguish them, but mixing them is bad style.NSNull— the singleton[NSNull null], a placeholder object meaning "value absent" for collections:NSArray/NSDictionarycannot holdnil(inserting it crashes withNSInvalidArgumentException), whileNSNullis an ordinary object you can store and compare by pointer.
#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