A class is said to conform to a formal protocol if it adopts the protocol or inherits from another class that adopts it. An instance of a class is said to conform to the same set of protocols its class conforms to.
Since a class must implement all the required methods declared in the protocols it adopts, saying that a class or an instance conforms to a protocol is equivalent to saying that it has in its repertoire all the methods the protocol declares.
It’s possible to check whether an object conforms to a protocol by sending it a conformsToProtocol: message.
if ( ! [receiver conformsToProtocol:@protocol(MyXMLSupport)] ) { |
// Object does not conform to MyXMLSupport protocol |
// If you are expecting receiver to implement methods declared in the |
// MyXMLSupport protocol, this is probably an error |
} |
(Note that there is also a class method with the same name—conformsToProtocol:.)
The conformsToProtocol: test is like the respondsToSelector: test for a single method, except that it tests whether a protocol has been adopted (and presumably all the methods it declares implemented) rather than just whether one particular method has been implemented. Because it checks for a all the methods in the protocol, conformsToProtocol: can be more efficient than respondsToSelector:.
The conformsToProtocol: test is also like the isKindOfClass: test, except that it tests for a type based on a protocol rather than a type based on the inheritance hierarchy.
Last updated: 2008-02-05