objective-cprotocolsstandards-compliancedefault-implementationoverhead-minimization

How do I provide a default implementation for an Objective-C protocol?


I'd like to specify an Objective-C protocol with an optional routine. When the routine is not implemented by a class conforming to the protocol I'd like to use a default implementation in its place. Is there a place in the protocol itself where I can define this default implementation? If not, what is the best practice to reduce copying and pasting this default implementation all over the place?


Solution

  • Objective-C protocols have no affordance for default implementations. They are purely collections of method declarations (and or properties) that may be implemented by conforming classes. A standard practice is to test an object at runtime to see if it responds to the given Selector before calling that method on it, using -[NSObject respondsToSelector:]. If the object does not respond to the selector, that method isn't called.

    One way you could achieve the result you're looking for would be to define a method encapsulating the default behavior you're looking for in the calling class, and call that method if the object doesn't pass the test.

    Another approach would be to make the method be required in the protocol, and provide default implementations in the superclasses of any classes wherein you may not want to provide a specific implementation.

    There are probably other options as well, but generally speaking there isn't a particular standard practice in Objective-C, except perhaps to just not call the given method if it hasn't been implemented by the object, per my first paragraph, above.