首页 > 代码库 > protocol

protocol

For every object that can have a delegate, there is a corresponding protocol that declares the
messages that the object can send its delegate. The delegate implements methods from the protocol for
events it is interested in. When a class implements methods from a protocol, it is said to conform to
the protocol.

 

Note that a protocol is not a class; it is simply a list of method declarations. You cannot create
instances of a protocol, it cannot have instance variables, and these methods are not implemented
anywhere in the protocol. Instead, implementation is left to each class that conforms to the protocol.

 

Before sending an optional message, the object first asks its delegate if it is okay to send that message
by sending another message, respondsToSelector:. Every object implements this method, which
checks at runtime whether an object implements a given method.

 

If a method in a protocol is required, then the message will be sent without checking first. This means
that if the delegate does not implement that method, an unrecognized selector exception will be
thrown, and the application will crash.

 

To prevent this from happening, the compiler will insist that a class implement the required methods
in a protocol. But for the compiler to know to check for implementations of a protocol’s required
methods, the class must explicitly state that it conforms to a protocol. This is done either in the class
header file or the class extension: the protocols that a class conforms to are added to a commadelimited
list inside angled brackets in the interface declaration.

protocol