Optional Methods

A protocol can explicitly designate some or all of its methods as optional. The question thus arises: How, in practice, is such an optional method feasible? We know that if a message is sent to an object and the object can’t handle that message, an exception is raised (and your app will likely crash). But a method declaration is a contract suggesting that the object can handle that message. If we subvert that contract by declaring a method that might or might not be implemented, aren’t we inviting crashes?

The answer is that Objective-C is not only dynamic but also introspective. You can ask an object whether it can deal with a message without actually sending it that message. This makes optional methods quite safe, provided you know that a method is optional.

The key method here is NSObject’s respondsToSelector:, which takes a selector parameter and returns a BOOL. With it, you can send a message to an object only if it would be safe to do so:

MyClass* mc = [MyClass new];
if ([mc respondsToSelector:@selector(woohoo)]) {
    [mc woohoo];
}

You wouldn’t want to do this before sending just any old message, because it isn’t necessary except for optional methods, and it slows things down a little. But Cocoa does in fact call respondsToSelector: on your objects as a matter of course. To see that this is true, implement respondsToSelector: on AppDelegate in our Empty Window project and instrument it with logging:

- (BOOL) respondsToSelector: (SEL) sel { NSLog(@"%@", NSStringFromSelector(sel)); ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.