Mobile Zone is brought to you in partnership with:

Programmed Macs since Inside Mac came in 3-ring binders; programmed iPhones since the first day the SDK was downloadable. 51 apps in the App Store to date, and always looking for new and interesting contracts! Alex is a DZone MVB and is not an employee of DZone and has posted 144 posts at DZone. You can read more from them at their website. View Full User Profile

iOS Tip: doesNotRecognizeSelector

  • submit to reddit

Here’s a handy piece of the Cocoa runtime you might have overlooked:


Handles messages the receiver doesn’t recognize.

- (void)doesNotRecognizeSelector:(SEL)aSelector

The runtime system invokes this method whenever an object receives an aSelector message it can’t respond to or forward. This method, in turn, raises an NSInvalidArgumentException, and generates an error message.

Any doesNotRecognizeSelector: messages are generally sent only by the runtime system. However, they can be used in program code to prevent a method from being inherited. For example, an NSObject subclass might renounce the copy or init method by re-implementing it to include a doesNotRecognizeSelector: message as follows:

- (id)copy { [self doesNotRecognizeSelector:_cmd]; }

Came to our attention via this tweet suggesting that the exception-throwiing pattern there was a good one to adopt in your base classes for methods intended to be overridden. Well, true enough, although we generally tend to design our base classes so that there is sensible … or at least non-fatal … default behaviour; however, it struck us that one particularly hard to debug problem this pattern would save us from is people who create an object without using the designated initializer. Yeah, all those of you out there who work in teams larger than one are nodding in agreement there, aren’t you? Indeed, you can see from the “or init” mention in the discussion there Apple positively endorses that approach. We believe we’ll make an immediate resolution to adopt that practice from now on; if there’s a designated initializer, make it actually IMPOSSIBLE not to use it!

Published at DZone with permission of Alex Curylo, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)