177

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Biranchi
  • 16,120
  • 23
  • 124
  • 161
  • 4
    Its related to Objective C question. – Biranchi Oct 14 '09 at 05:37
  • `nil` means a kind of `NULL` for objc instance. So you can mark specific value is intended for objc instance or generic pointer. In view of type management and safety, this will help you a lot. – eonil Apr 10 '11 at 03:54
  • 4
    `nil` and `null`/`NULL` are the same -- both defined to be zero. As a formality, use `nil` when coding Objective-C and `NULL` when coding regular C/C++ statements/calls. `NSNull` is something entirely different, however. It's a singleton object that serves as a place-holder to represent "nothing" in, eg, NSDictionarys where nil/null pointers are not allowed. – Hot Licks Mar 27 '12 at 03:23
  • Refer link for good explanation [here][1] [1]: http://stackoverflow.com/questions/5908936/iphonedifference-between-nil-nil-and-null – Ameer Jun 05 '13 at 10:41
  • 1
    possible duplicate of [NULL vs nil in Objective-C](http://stackoverflow.com/questions/557582/null-vs-nil-in-objective-c) – awiebe Jul 08 '13 at 08:52
  • http://nshipster.com/nil/ – mfaani Apr 26 '16 at 14:14

16 Answers16

325

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
  • 16,861
  • 7
  • 32
  • 46
  • 14
    Best explanation I have heard of the difference (: Thanks. – Jay Oct 14 '09 at 12:58
  • 3
    This should be the accepted answer, not because there are more up-votes, but because it has the best explanation to the question posed. – James Mertz Jun 08 '12 at 03:51
  • 6
    Elegant description of `NULL` v `nil`, but this seriously misses the mark re `[NSNull null]`. See [Using NSNull](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/NumbersandValues/Articles/Null.html) section of _Number and Value Programming Topics_ and [NSNull Class Reference](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/Reference/Reference.html). – Rob Nov 17 '12 at 15:04
  • Both seem to be pointers to `void *`. A different answer here already mentions this, but if you dig into `objc.h`, you'll find the line `#define nill __DARWIN_NULL`. – gkb0986 Oct 25 '13 at 03:12
  • 1
    This answer sounds good but according to the other answers it's simply incorrect. – n13 Mar 26 '14 at 06:11
  • Greg, when did this change? I remember that NULL, Nil and nil were the same on NextStep. – NSResponder Mar 29 '14 at 22:42
120

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex
  • 4,316
  • 2
  • 24
  • 28
  • 14
    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 Oct 14 '09 at 05:43
  • 42
    also, in MacTypes.h there is `#define nil NULL` – cobbal Oct 14 '09 at 05:46
  • 8
    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 Oct 14 '09 at 07:11
  • 18
    This accepted answer fails to acknowledge that `[NSNull null]` is a very different beast. To quote from [NSNull Class Reference](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/Reference/Reference.html), "The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values)." Also see [Using NSNull](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/NumbersandValues/Articles/Null.html) section of _Number and Value Programming Topics._ – Rob Nov 17 '12 at 15:13
  • "The main difference is that you can send messages to nil" - you can send messages to `NULL` as well. –  Feb 09 '13 at 09:27
  • I guess that there was a difference historically, but there isn't anymore at this point. This is still a good answer: "In general, just use nil" so I am leaving the up vote. – n13 Mar 26 '14 at 06:13
  • Please share example where we can't use NULL. – Anjali jariwala Oct 24 '18 at 13:08
  • This was a main cause of ios facebook issue https://github.com/facebook/facebook-ios-sdk/issues/1430 LOL – MJ Studio Jul 11 '20 at 04:19
30

nil is an empty value bound/corresponding with an object (the id type in Objective-C). nil got no reference/address, just an empty value.

NSString *str = nil;

So nil should be used, if we are dealing with an object.

if(str==nil)
    NSLog("str is empty");

Now NULL is used for non-object pointer (like a C pointer) in Objective-C. Like nil , NULL got no value nor address.

char *myChar = NULL;
struct MyStruct *dStruct = NULL;

So if there is a situation, when I need to check my struct (structure type variable) is empty or not then, I will use:

if (dStruct == NULL)
    NSLog("The struct is empty");

Let’s have another example, the

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

Of key-value observing, the context should be a C pointer or an object reference. Here for the context we can not use nil; we have to use NULL.

Finally the NSNull class defines a singleton object used to represent null values in collection objects(NSArray, NSDictionary). The [NSNull null] will returns the singleton instance of NSNull. Basically [NSNull null] is a proper object.

There is no way to insert a nil object into a collection type object. Let's have an example:

NSMutableArray *check = [[NSMutableArray alloc] init];
[check addObject:[NSNull null]];
[check addObject:nil];

On the second line, we will not get any error, because it is perfectly fair to insert a NSNull object into a collection type object. On the third line, we will get "object cannot be nil" error. Because nil is not an object.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shad
  • 1,587
  • 2
  • 20
  • 29
20

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

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Chuck
  • 234,037
  • 30
  • 302
  • 389
13

I've found the following:

objc.h

#define Nil __DARWIN_NULL   /* id of Nil class */
#define nil __DARWIN_NULL   /* id of Nil instance */

_types.h

#define __DARWIN_NULL ((void *)0)

stddef.h

#undef NULL
#ifdef __cplusplus
#undef __null  // VC++ hack.
#define NULL __null
#else
#define NULL ((void*)0)
#endif

MacTypes.h

#ifndef NULL
#define NULL    __DARWIN_NULL
#endif /* ! NULL */
#ifndef nil
    #define nil NULL
#endif /* ! nil */

The way it looks, there's no difference but a conceptual one.

colnaghi
  • 481
  • 5
  • 9
8

Beware that if([NSNull null]) returns true.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nicolas Manzini
  • 8,379
  • 6
  • 63
  • 81
7

They both are just typecast zero's. Functionally, there's no difference between them. ie.,

#define NULL ((void*)0)
#define nil ((id)0)

There is a difference, but only to yourself and other humans that read the code, the compiler doesn't care.

One more thing nil is an object value while NULL is a generic pointer value.

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
Nirav Jain
  • 5,088
  • 5
  • 40
  • 61
6

In modern OS X and iOS SDKs:

  • nil and Nil and NULL are identical in Objective-C and in Objective-C++ before C++11.
  • nil and Nil and std::nullptr are identical in Objective-C++ with C++11.

Stylistically, many people prefer to use nil for Objective-C objects and NULL or nullptr for other pointer types. I myself now use nil everywhere.

[NSNull null] is a singleton object use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an NSArray or NSDictionary). Number and Value Programming Topics: Using NSNull

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Greg Parker
  • 7,972
  • 2
  • 24
  • 21
5

To expand on a comment from @cobbal:

MacTypes.h contains:

#ifndef nil
   #define nil NULL
#endif
Justin Tanner
  • 14,062
  • 17
  • 82
  • 103
4

As already mentioned, they are the same, but I use either the one or the other depending on the language in which the corresponding framework was written.

For everything related to Objective-C, I use nil. For example:

- (BOOL)doSomethingWithObjectsInArray:(NSArray *)anArray {
    if (anArray == nil) return NO;

    // process elements
    ...
}

However, when checking validity of data models from a C-framework (like AddressBook framework and CoreFoundation), I use NULL. For example:

- (BOOL)showABUnknownPersonVCForABRecordRef:(ABRecordRef)aRecord {
    if (aRecord == NULL) return NO;

    // set-up the ABUnknownPersonViewController and display it on screen
    ..
}

This way, I have subtle clues in my code if I'm dealing with Obj-C or C based code.

Tafkadasoh
  • 4,667
  • 4
  • 27
  • 31
4

nil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another.

On the framework level, Foundation defines NSNull, which defines a class method, +null, which returns the singleton NSNull object. NSNull is different from nil or NULL, in that it is an actual object, rather than a zero value.

Additionally, in Foundation/NSObjCRuntime.h, Nil is defined as a class pointer to nothing.

Refer this for further info - nil / Nil / NULL / NSNull

3

There is a difference in some contexts.

Literally, Null is a character: ASCII 0.

Nil is equivalent to blank, no value.

Depending on the programming context, this can be a big difference.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Meatloaf
  • 1
  • 2
1

Use NULL for example when you invoke an Objective-C method with an output parameter of type (NSError **).

I see lots of example code on the web where people provide nil instead of NULL in this case. This is because it's a pointer to a pointer and thus not directly an Objective-C object type. As said above, nil should be used for Objective-C object types.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bio
  • 669
  • 4
  • 14
1

Basically: nil: null pointer on an object and null: is for other type pointer

gerachev
  • 121
  • 1
  • 4
0

nil means absence of value while NULL represent No Object,

NSArray *array = @[@"Hello World !", @101,[NSNULL null] ];

Here [NSNULL null] is an object which means no object, at the same time you cannot add nil to indicate absence of object.

you can use both nil and [NSNUll null] for checking too.

Roshan Sah
  • 137
  • 10
0

This will help you to understand the difference between nil, NIL and null.

The below link may help you in some way:

http://nshipster.com/nil/

nil -> literal null value for Objective-C objects.

Nil -> literal null value for Objective-C classes.

NULL -> literal null value for C pointers.

NSNULL -> singleton object used to represent null.

Florian Koch
  • 1,372
  • 1
  • 30
  • 49