A protocol declares methods that can be implemented by any class. It is not a class itself, but it defines a set of methods that objects conforming to it are responsible for implementing. This is the same concept as an interface in Java.

@protocol is similar to @interface, but we don’t need to worry about the implementing. It is also declared in a header file.

Let’s add a protocol for our Animal.

Header Source

A protocol can extend another protocol.

Header Source

A protocol can have optional methods.

Header Source

We can declare variables that conform to a protocol without implementing a specific class.

The main use for protocols in Cocoa is for delegates and data sources.

A delegate is a responder object that acts on behalf of, or in coordination with, another object when that object encounters a user event in a program. The delegate is asked to interpret that event in an application-specific manner.

For example, the ViewController in our FeedTheCat app is a delegate for the “Touch Up Inside” event on the UIButtons in the view.

A data source is like a delegate except that, instead of being delegated control of the user interface, it is delegated control of data.

  1. Protocols. Learning Objective-C: A Primer. Apple, Sep 1 2010.

  2. Delegates and Data Sources. Cocoa Fundamentals Guide. Apple, Dec 13 2010.

Comments are closed.