nil / NULL / NSNull / Optionals

In Objective-C, there are three different varieties of nothing . The reason for this goes back to how Objective-C bridges the procedural paradigm of C with Smalltalk-inspired object-oriented paradigm.

C represents nothing as 0 for primitive values, and NULL for pointers (which is equivalent to 0 in a pointer context).

Objective-C builds on C’s representation of nothing by adding nil. 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.

What you ever want to  know about nil

Newly-alloced NSObjects start life with their contents set memory initialised with 0. This means that all pointers that object has to other objects begin as nil where non referencing variables have the value 0.

But perhaps the most notable behavior of nil, though, is that it can have messages sent to it. In other languages, like C++ or Java, this would crash your program, but in Objective-C, invoking a method on nil returns a zero value.

Being aware of how nil works in Objective-C allows this convenience to be a feature, and not a lurking bug in your application. Make sure to guard against cases where nil values are unwanted, either by checking and returning early to fail silently, or adding a NSParameterAssert to throw an exception.

NSNull: An Object for Nothing

NSNull is used throughout Foundation and other frameworks to skirt around the limitations of collections like NSArray and NSDictionary not being able to contain nil values. You can think of NSNull as effectively boxing the NULL or nil value so that it can be used in collections.

Swift Optionals versus nil

Swift introduces optional types, which handle the absence of a value – even for non object types. Optionals say either “there is a value, and it is equals s” or “there isn’t a value at all”. Using optionals is similar to using nil with pointers in Objective-C. but they work for any type, not just classes. Optionals are safer and more expressive then nil pointers in Objective-C so it is time to change your mind!

tomkausch

Leave a Reply

Your email address will not be published. Required fields are marked *