Chapter 7. Working with Protocols

In This Chapter

  • Solving object-oriented design problems with protocols

  • Implementing protocols for your classes

  • Adopting protocols

  • Working with optional methods

  • Understanding formal versus informal protocols

Objective-C does not feature multiple inheritance, which has advantages as well as disadvantages. It is advantageous because multiple inheritance results in complicated issues that can be difficult to resolve. However, it is also a disadvantage because there are times when you want to have a class, which implements a specific interface without necessarily inheriting from the class that specifies that interface. Thankfully, the designers of Objective-C included a feature to address exactly this situation, protocols.

Essentially, a protocol defines an interface that can be implemented by multiple other classes without the use of inheritance. This enables you to mix and match functionality on a given class so that the class can be adapted to different uses.

Favoring Composition Over Inheritance

An object oriented design axiom known as "favor composition over inheritance" means that rather than always turning to inheritance as a tool for extending functionality of a given class, you should instead first try to solve the problem by using other classes compositionally within your class. For example, if you needed to implement a class that provided an interface between a network service and your application, instead of inheriting from a socket class (a class ...

Get Objective-C 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.