Search code examples
objective-cnullnsnull

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


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]?


Solution

  • You can use nil about anywhere you can use null. The main difference is that you can send messages to nil, so you can use it in some places where null cant work.

    In general, just use nil.