Header Ads

Protocols - Objective C

Objective C allow you to define protocol, which declare the methods expected to be used for a particular situation. Protocols are implemented in the classes confirming to the protocol.

A simple example would be network URL handling class, it will have a protocol with methods like processCompleted delegate method that intimates the calling class once the network URL fetching operation is over.

A syntax of protocol is shown below:

@protocol ProtocolName
@required
      //list of required method
@optional
     //list of optional method
@end


The methods under keyword @required must be implemented in the classes that confirms to the protocol and the method under @optional keyword are optional to implement.

Here is the syntax for class confirming to protocol.

@interface MyClass : NSObject <MyProtocol>
....
@end


This means that any instance MyClass will respond not only to the methods declared specifically in the interface, but MyClass also provides implementations for the required methods in MyProtocol. There's no need to redeclare the protocol  methods in the class interface - the adoption of the protocol is sufficient.

If you need a class to adopt multiple protocols, you can specify them as comma-separed list. We have a delegate object that holds the reference of the calling object that implements the protocol.

An example is shown below

#import <Foundation/Foundation.h>
@protocol printProtocolDelegate

    - (void) processsCompleted;

@end

@interface PrintClass : NSObject
{
     id delegate;
}
   -(void) printDetails;
   -(void) setDelegate : (id)newDelegate;

@end

@implementation PrintClass

   -(void)printDetails
    {
             NSLog(@"Printing Details");
    }
  -(void) setDelegate : (id)newDelegate
  {
     delegate = newDelegate;
  }
@end

@interface SampleClass :NSObject
  
    -(void)startAction;
@end

@implementation SampleClass

   - (void)startAction
    {
              PrintClass *print = [[PrintClass alloc]init];
              [print setDelegate :self];
             [ print printDetails];
    }
    - (void) processCompleted
       {
            NSLog(@"PRinting process Completed");
      }
@end

int main(int argc , const char * argv[])
{
        SampleClass *sam = [[SampleClass alloc]init];
        [sam startAction];
        return 0;
}
 

In the above example we have seen how the delegate methods are called and executed. Its start with startAction , once the process is completed , the delegate method processCompleted is called to intimate the operation is completed.

In ant IOS or Mac app , we will never have a program implemented without a delegate. SO its important we understand the usage of delegates . Delegates objects should use unsafe_unretained property type avoid memory leaks.


No comments:

Powered by Blogger.