views:

1033

answers:

3

This is a 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 to use nil, NULL and [NSNULL null] ?

Thanks

+2  A: 

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.

Alex
technically, they are exactly equal, you can send messages to both nil and to NULL. Idiomatically though nil is usually used to represent an object
cobbal
also, in MacTypes.h there is `#define nil NULL`
cobbal
Yeah, as cobbal says, they are the same. It is more a contextual reference where NULL is a pointer to 0x0, nil is a non-existent objective-c object and Nil is a non-existent objective-c class, but technically they are all just 0. Also, it is NULL not null -- null is in Java or C# but not in Objective-C.
Jason Coco
+7  A: 

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

NSResponder
Best explanation I have heard of the difference (: Thanks.
Jacob
+4  A: 

NULL and nil are equal to each other, but nil is an object value while NULL is a generic pointer value ((void*)0, to be specific). [NSNull null] is an object that's meant to stand in for nil in situations where nil isn't allowed. For example, you can't have a nil value in an NSArray. So if you need to represent a "nil", you can use [NSNull null.

Chuck