Protocols and Delegates
A protocol declares methods that can be implemented by any class. Protocols are not classes themselves. They simply define an interface that other objects are responsible for implementing. When you implement the methods of a protocol in one of your classes, your class is said to conform to that protocol.
Protocols are used frequently to specify the interface for delegate objects. A delegate object is an object that acts on behalf of, or in coordination with, another object. The best way to look at the interplay between protocols, delegates, and other objects is to look at an example.
The UIApplication
class implements the required behavior of an application. Instead of forcing you to subclass UIApplication
to receive simple notifications about the current state of the application, the UIApplication
class delivers those notifications by calling specific methods of its assigned delegate object. An object that implements the methods of the UIApplicationDelegate
protocol can receive those notifications and provide an appropriate response.
The declaration of a protocol looks similar to that of a class interface, with the exceptions that protocols do not have a parent class and they do not define instance variables. The following example shows a simple protocol declaration with one method:
@protocol MyProtocol |
- (void)myProtocolMethod; |
@end |
No comments:
Post a Comment