Over a million developers have joined DZone.
Platinum Partner

iOS Tip: doesNotRecognizeSelector

· Mobile Zone

The Mobile Zone is brought to you in partnership with CA Technologies.  Spending too much time coding your mobile backend? CA Mobile App Services does the work for you.

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!

The Mobile Zone is brought to you in partnership with CA Technologies. Read the ebook: Accelerating Enterprise Mobile and IoT App Development to learn more.


Published at DZone with permission of Alex Curylo , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}