1.19. Delegating Tasks with Protocols
Problem
You want to make sure a certain object implements a set of methods or properties.
Solution
Use a protocol.
Discussion
A protocol is the declaration (as opposed to implementation) of a set of methods and/or properties in a header file (usually with the extension of .h). Any object that you declare to conform to such protocol is responsible for writing the implementation of those methods and properties, depending on whether the protocol specifies them as required or optional.
Think of protocols as set of rules (some rules being optional
and some mandatory). Any object saying that it conforms to that
protocol must follow those rules. Let’s see a simple example of this.
We will go ahead and define a protocol called PersonProtocol. For this, you need to create
a new protocol file, so follow these steps first:
In Xcode, while your project is open, go to the File menu and then choose New→New File...
Now make sure iOS is the main category on the left side of the New File dialog and then choose the Cocoa Touch subcategory. Once that is done, choose the Objective-C Protocol item and press Next (see Figure 1-26).
Now you will be asked to save this file and specify a name for it. Give it the name
PersonProtocoland press Save (see Figure 1-27).
Now we have our header file. Let’s get on with the actual
declaration of our protocol. Our objective with this new PersonProtocol protocol is to govern the rules on any class that impersonates a “Person”, or in other ...
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