WILTAC #1: invoking methods on nil in Objective-C

Welcome to the first installment of “What I learned today about Cocoa” (WILTAC).

I have recently started reading Aaron Hillegass’ excellent Cocoa Programming for Mac OS X, third edition, with the intention of brushing up my very lacking Cocoa skills (all of them learned empirically by looking at other people’s code and reading the documentation). To motivate myself to actually make progress, I have decided to write every day (if possible) a short post describing something interesting I learned. Seasoned Cocoa developers might want to skip this, I’m doing it mostly for my own benefit. So without further ado, here’s the thing I learned today:

In Objective-C, you can invoke methods on nil objects, without causing an error

Not a Cocoa-specific tip, but very interesting nonetheless. And a possible source of hard-to-track errors, if you are not careful and try to call methods on nil objects assuming they are not nil.

One interesting bit is that if the receiving object is of type “id”, it seemingly will accept any method, as long as it is defined for some class. If the method is not defined anywhere, you do get a “warning: no -foobaz method”. If the variable is defined as some specific class, it will accept all the methods for that class, and give appropriate warning for methods from other classes or nonexistent methods.


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