Objective-C has a neat little thing called nil, which represents the absence of an object. It’s like null in Java or JavaScript, or NULL in C, but with one important difference: you can call methods on it.
“Bwah?” you say, wondering why that would be a feature rather than a bug. Yes, that was my first reaction too. But after much use, I have decided that it is indeed a feature.
Send a message (i.e. call a method) — any message — to nil, and the response is always 0, i.e. nil. It’s counter-intuitive that nil is a good thing, because it seems like it would be a good way to mask errors.
And it can mask errors, but not usually. More importantly, effective use of nil cleans up tons of code that would otherwise be filled with if (foo == nil) checks.
Consider: object X holds a delegate “foo” which is notified about various events that happen to X. This delegate foo is connected to X by code external to both X and foo.
Now, this foo thingy isn’t really essential to the proper functioning of X. X doesn’t care about foo, foo cares about X. So why in the world should X be responsible for figuring out whether foo has been set or not?
Enter nil. X doesn’t need to know whether it’s delegate foo has been set or not, it just sends messages. If there’s no foo there, the messages disappear into the ether. Meanwhile X’s code is easier to read, because it doesn’t jump through hoops to guarantee that foo present.
I like nil. A lot.
(Update: some commenters have expressed concern about the effect of nil within arithmetic operations. It’s an understandable concern, but not relevant to Objective-C. Nil is an object type, not a primitive type. And as those of you familiar with C and Objective-C already know, primitive types don’t coerce to objects, and there’s no operator overloading. So nil doesn’t ever participate in arithmetic operations.)