Adopting a protocol is similar in some ways to declaring a superclass. Both assign methods to the class. The superclass declaration assigns it inherited methods; the protocol assigns it methods declared in the protocol list. A class is said to adopt a formal protocol if in its declaration it lists the protocol within angle brackets after the superclass name:
@interface ClassName : ItsSuperclass < protocol list > |
Categories adopt protocols in much the same way:
@interface ClassName ( CategoryName ) < protocol list > |
A class can adopt more than one protocol; names in the protocol list are separated by commas.
@interface Formatter : NSObject < Formatting, Prettifying > |
A class or category that adopts a protocol must implement all the required methods the protocol declares, otherwise the compiler issues a warning. The Formatter class above would define all the required methods declared in the two protocols it adopts, in addition to any it might have declared itself.
A class or category that adopts a protocol must import the header file where the protocol is declared. The methods declared in the adopted protocol are not declared elsewhere in the class or category interface.
It’s possible for a class to simply adopt protocols and declare no other methods. For example, the following class declaration adopts the Formatting and Prettifying protocols, but declares no instance variables or methods of its own:
@interface Formatter : NSObject < Formatting, Prettifying > |
@end |
Last updated: 2008-02-05