Just as classes are represented at runtime by class objects and methods by selector codes, formal protocols are represented by a special data type—instances of the Protocol class. Source code that deals with a protocol (other than to use it in a type specification) must refer to the Protocol object.
In many ways, protocols are similar to class definitions. They both declare methods, and at runtime they’re both represented by objects—classes by class objects and protocols by Protocol objects. Like class objects, Protocol objects are created automatically from the definitions and declarations found in source code and are used by the runtime system. They’re not allocated and initialized in program source code.
Source code can refer to a Protocol object using the @protocol() directive—the same directive that declares a protocol, except that here it has a set of trailing parentheses. The parentheses enclose the protocol name:
Protocol *myXMLSupportProtocol = @protocol(MyXMLSupport); |
This is the only way that source code can conjure up a Protocol object. Unlike a class name, a protocol name doesn’t designate the object—except inside @protocol().
The compiler creates a Protocol object for each protocol declaration it encounters, but only if the protocol is also:
Adopted by a class, or
Referred to somewhere in source code (using @protocol())
Protocols that are declared but not used (except for type checking as described below) aren’t represented by Protocol objects at runtime.
Last updated: 2008-02-05