When should I use nil and NULL in Objective-C?

Biranchi picture Biranchi · Oct 14, 2009 · Viewed 118.8k times · Source

This is sample code:

NSDictionary *myDictionary = [NSDictionary dictionary];
NSNumber *myNumber = [myDictionary valueForKey: @"MyNumber"];
NSLog(@"myNumber = %@", myNumber); // output myNumber = (null)

if (myNumber == nil)
    NSLog(@"test 1 myNumber == nil");

if (myNumber == NULL)
    NSLog(@"test 2 myNumber == NULL");

if ([myNumber isEqual:[NSNull null]])
    NSLog(@"test 3 myNumber == [NSNull null]");

When should I use nil, NULL and [NSNull null]?

Answer

NSResponder picture NSResponder · Oct 14, 2009

They differ in their types. They're all zero, but NULL is a void *, nil is an id, and Nil is a Class pointer.