A protocol is a list of method declarations that is not bound to any one class. The methods are not implemented in the protocol; instead, classes conform to or adopt a protocol and within those classes the methods are implemented. A protocol is simply a grouping of certain related methods under one name, and it acts like a contract—conforming classes must implement the required methods (and may implement any of the potential optional methods).
Here is an example of a protocol which includes one method, notice the instance variable delegate is of type id, as it will be unknown at compile time the type of class that will adopt this protocol.
#import< Foundation/Foundation.h>
@protocol ProcessDelegate< NSObject>
@required
- (void) processSuccessful: (BOOL)success;
@end
@interface ClassWithProtocol : NSObject {
id <ProcessDelegate> delegate;
}
@property (retain) id delegate;
-(void)startSomeProcess;
@end
Protocol Implementation
Inside the implementation section for the interface defined above we need to do two things at a minimum – first synthesize the delegate instance variable and second, call the method defined in the protocol as needed (more on that in a moment).
Let’s look at a bare bones implementation of the SampleWithProtocol.m:
Tarun Kumar
21-Jul-2015A protocol is a list of method declarations that is not bound to any one class. The methods are not implemented in the protocol; instead, classes conform to or adopt a protocol and within those classes the methods are implemented. A protocol is simply a grouping of certain related methods under one name, and it acts like a contract—conforming classes must implement the required methods (and may implement any of the potential optional methods).
Here is an example of a protocol which includes one method, notice the instance variable delegate is of type id, as it will be unknown at compile time the type of class that will adopt this protocol.
Protocol Implementation
Inside the implementation section for the interface defined above we need to do two things at a minimum – first synthesize the delegate instance variable and second, call the method defined in the protocol as needed (more on that in a moment).
Let’s look at a bare bones implementation of the SampleWithProtocol.m: