2 Feb 2013

Objective-C: messaging to nil

When you call methods in Objective-C you're sending messages (to objects or classes). In many object-oriented languages sending a message to a null pointer crashes your program, in Objective-C it doesn't :)

In Objective-C you can happily run the following code without fear because it simply does nothing, no code gets executed.

In Java instead you get a null pointer exception at runtime:

So in Objective-C you don't have to write a lot of if(pointer != null) checks (as you have to in other languages). However it's good to remember that Objective-C implicitly initialises all pointers to nil, so if your messages simply do nothing, check the receiver, probably it's pointing to nil!

If a method returns a value and is called on a nil receiver, then 0 is returned. But there's an exception to this (caveat), if a method returns a C struct then undefined is returned instead of 0.