Optional Methods
The careful reader may have noticed that earlier sections of this chapter have listed two ways in which a method can be publicly declared without necessarily being implemented, and without the compiler complaining if it isn’t:
- By defining a named category interface section with no corresponding named category implementation section.
- By defining a protocol in which some methods are explicitly designated 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 alloc] init];
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access