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

Solution 1:

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 2:

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