Tarun Kumar

Total Post:0

Posted by  Tarun Kumar
 925  View(s)
Rate this:
  1. Tarun Kumar


    What is protocol?

    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>


    - (void) processSuccessful: (BOOL)success;



    @interface ClassWithProtocol : NSObject {

     id <ProcessDelegate> delegate;



    @property (retain) id delegate; 




    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:

    #import "ClassWithProtocol.h" 


    @implementation ClassWithProtocol


    @synthesize delegate;

    - (void)processComplete {

      [[self delegate] processSuccessful:YES];


    -(void)startSomeProcess {

      [NSTimer scheduledTimerWithTimeInterval:5.0 target:self

        selector:@selector(processComplete) userInfo:nil repeats:YES];



      Modified On Mar-28-2018 04:46:54 AM



Enter your email address here always to be updated. We promise not to spam!