Type declarations for objects can be extended to include formal protocols. Protocols thus offer the possibility of another level of type checking by the compiler, one that’s more abstract since it’s not tied to particular implementations.
In a type declaration, protocol names are listed between angle brackets after the type name:
- (id <Formatting>)formattingService; |
id <MyXMLSupport> anObject; |
Just as static typing permits the compiler to test for a type based on the class hierarchy, this syntax permits the compiler to test for a type based on conformance to a protocol.
For example, if Formatter is an abstract class, this declaration
Formatter *anObject; |
groups all objects that inherit from Formatter into a type and permits the compiler to check assignments against that type.
Similarly, this declaration,
id <Formatting> anObject; |
groups all objects that conform to the Formatting protocol into a type, regardless of their positions in the class hierarchy. The compiler can make sure only objects that conform to the protocol are assigned to the type.
In each case, the type groups similar objects—either because they share a common inheritance, or because they converge on a common set of methods.
The two types can be combined in a single declaration:
Formatter <Formatting> *anObject; |
Protocols can’t be used to type class objects. Only instances can be statically typed to a protocol, just as only instances can be statically typed to a class. (However, at runtime, both classes and instances will respond to a conformsToProtocol: message.)
Last updated: 2008-02-05