Difference between nil vs NULL vs NSNull

There are three ways to represent a null value in Objective-C.

nil = Absence of value with Objective-C object variables

NULL = Absence of a value with C-style pointers
NSNull = A nil boxed as an object for storage in a collection.

If you try adding nil to a NSDictionary or NSArray, you will find out it doesn’t perform as expected.  If you absolutely need to store a null value in a collection, you can use NSNull to represent the lack of a value.  For example:

NSNull nullValue = [NSNull null];
[anArray addObject:nullValue];

Note, however, that since NSNull represents the lack of a value, there is no way to retrieve that value from the collection. In order to determine if there is no value for a particular key or index, you must compare against NSNull.

id value = [anArray objectAtIndex:3];
if (value == [NSNull null]) {
  // Do something for a null
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s