Objective-C Duck Punching

Objective-C is a cool language for many reasons. One reason is that it’s a dynamic language that allows you to do all kinds of fun things at runtime. Allas one of those features has gone away with the introduction to ARC.

Once upon a time you could send any message you like to an Objective-C object and it would try to respond. If you inherited from NSObject you could make use of the invocationForwarding method to handle any method you didn’t expressly implement. Over time the compiler got smarter and wouldn’t let you send just any message to Objective-C objects so you had to switch to using the id type. id would catch anything. This is no more.

I came across this thread ARC: error: no known instance method for selector. One of the contributors to the thread, John McCall of Apple, made the following statement:

Our reasoning was split about 50/50 between (1) needing to be more careful about types and ownership and (2) wanting to eliminate an embarrassing wart in the language (not being allowed to complain about completely unknown methods with anything more strenuous than a warning).  There is really no legitimate reason to call a method that's not even declared somewhere.  The ability to do this makes some really trivial bugs (e.g. typos in selectors) runtime failures instead of compile failures.  We have always warned about it.  Fix your code.


You can follow the whole thread but the short is that Apple made the call to be more cautious about types and ownership and traded away the flexability of id. Is this the end of the world? Nah, it just takes out a nice little quirky feature of the language.

Leave a Reply

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