Protocol

A protocol declares a programmatic interface that any class may choose to implement. Protocols make it possible for two classes distantly related by inheritance to communicate with each other to accomplish a certain goal. They thus offer an alternative to subclassing. Any class that can provide behavior useful to other classes may declare a programmatic interface for vending that behavior anonymously. Any other class may choose to adopt the protocol and implement one or more of its methods, thereby making use of the behavior. The class that declares a protocol is expected to call the methods in the protocol if they are implemented by the protocol adopter.

Protocol

Formal and Informal Protocols

There are two varieties of protocol, formal and informal:

Adopting and Conforming to a Formal Protocol

A class can either declare adoption of a formal protocol or inherit adoption from a superclass. The adoption syntax uses angle brackets in the @interface declaration of the class. In the following example, the CAAnimation class declares its superclass to be NSObject and then formally adopts three protocols.

@interface CAAnimation : NSObject <NSCopying, CAMediaTiming, CAAction>

A class—and any instance of that class—are said to conform to a formal protocol if the class adopts the protocol or inherits from another class that adopts it. Conformance to a protocol also means that a class implements all the required methods of the protocol. You can determine at runtime whether an object conforms to a protocol by sending it a conformsToProtocol: message.

Creating Your Own Protocol

You may also declare your own protocol and implement the code that communicates with adopters of that protocol. For a description of how to do this, see the document that definitively describes protocols.

Definitive Discussion

Prerequisite Articles

Sample Code Projects

Did this document help you? Yes It's good, but... Not helpful...


Last updated: 2010-08-03