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

124,308

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

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

Solution 5

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.

Share:
124,308

Related videos on Youtube

Biranchi
Author by

Biranchi

Machine Learning enthusiast

Updated on February 15, 2020

Comments

  • Biranchi
    Biranchi over 4 years

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

    • Biranchi
      Biranchi over 14 years
      Its related to Objective C question.
    • eonil
      eonil about 13 years
      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.
    • Hot Licks
      Hot Licks over 12 years
      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.
    • Ameer
      Ameer about 11 years
      Refer link for good explanation [here][1] [1]: stackoverflow.com/questions/5908936/…
    • awiebe
      awiebe almost 11 years
      possible duplicate of NULL vs nil in Objective-C
    • mfaani
      mfaani about 8 years
  • cobbal
    cobbal over 14 years
    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
    cobbal over 14 years
    also, in MacTypes.h there is #define nil NULL
  • Jason Coco
    Jason Coco over 14 years
    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.
  • Jay
    Jay over 14 years
    Best explanation I have heard of the difference (: Thanks.
  • James Mertz
    James Mertz about 12 years
    This should be the accepted answer, not because there are more up-votes, but because it has the best explanation to the question posed.
  • Rob
    Rob over 11 years
    Elegant description of NULL v nil, but this seriously misses the mark re [NSNull null]. See Using NSNull section of Number and Value Programming Topics and NSNull Class Reference.
  • Rob
    Rob over 11 years
    This accepted answer fails to acknowledge that [NSNull null] is a very different beast. To quote from NSNull Class Reference, "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 section of Number and Value Programming Topics.
  • Admin
    Admin over 11 years
    "The main difference is that you can send messages to nil" - you can send messages to NULL as well.
  • gkb0986
    gkb0986 over 10 years
    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.
  • n13
    n13 over 10 years
    This answer sounds good but according to the other answers it's simply incorrect.
  • n13
    n13 over 10 years
    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.
  • NSResponder
    NSResponder about 10 years
    Greg, when did this change? I remember that NULL, Nil and nil were the same on NextStep.
  • Michael
    Michael about 10 years
    +1 for mentioning practical use of nil/null in array.
  • Florian Koch
    Florian Koch almost 7 years
    does this add anything new (which isn't covered by the existing answers)?
  • Anjali jariwala
    Anjali jariwala over 5 years
    Please share example where we can't use NULL.
  • MJ Studio
    MJ Studio almost 4 years
    This was a main cause of ios facebook issue github.com/facebook/facebook-ios-sdk/issues/1430 LOL