Friday, July 19, 2013

Objective-C Protocols

A protocol is a group of related properties and methods that can be implemented by any class. objective-c not supported multiple inheritance directly by achieving multiple inheritance we are using Protocols.


Like class interfaces, protocols typically reside in a .h file. To add a protocol to your Xcode project, navigate to File > New> File… or use the Cmd+N shortcut. Select Objective-C protocol under theiOS > Cocoa Touch category.





Creating a protocol in Xcode


In this module, we’ll be working with a protocol called StreetLegal. Enter this in the next window, and save it in the project root.





Example program using protocol:  my protocol name is Printing lets see below how to declare a protocol and methods.



#import


@protocol Printing <NSObject>

-(void) print;

@end

the above protocol declaration is over and i have declare one method -

if the protocol method is @Required  ex:

@Required
-(void)display

whenever you're using this protocol in child classes u must be implementing .m in child class.
suppose if declare a method using @Optional Ex:

@Optional
-(void)displayAll

this method is our optional to implementing in child class , below i show one example

#import 

@protocol Printing <NSObject>

@required

-(void) print;

@optional

-(void)displayAll;

@end


now i am taking two classes 1.Fraction and 2.Complex using this protocol how to access the protocol methods in classes and how to declare a protocol in classes below we can see those implementations.

Fraction class .h

#import "Printing.h"    //protocol imported to our fraction class

#import

@interface Fraction : NSObject<Printing>
{
   
}

@property (nonatomic) int numerator;

@property (nonatomic) int denominator;

-(Fraction*) initWithNumerator: (int) n denominator: (int) d;

@end

Fraction class .m

#import "Fraction.h"

@implementation Fraction

@synthesize numerator;

@synthesize denominator;

-(Fraction *)initWithNumerator:(int)n denominator:(int)d
{
  
   self = [super init];
   
   if ( self ) {
       self.numerator = n;
       self.denominator = d;
   }
  
   return self;
}

-(void) print
{
   NSLog(@ "%i/%i   ", self.numerator, self.denominator );
}


@end


you can observe above we are using print method (printing protocol) and we have print the numerator and denominator using print protocol method

2. Complex class .h

#import "Printing.h"

#import 

@interface Complex : NSObject <Printing>
{
   
}

@property (nonatomic) double real;
@property (nonatomic) double imaginary;

-(Complex*) initWithReal: (double) r andImaginary: (double) i;

@end

Complex class .m
#import "Complex.h"

@implementation Complex

@synthesize real;
@synthesize imaginary;

-(Complex*) initWithReal: (double) r andImaginary: (double) i
{
   self = [super init];
   
   if ( self ) {
       self.real = r;
       self.imaginary = i;
   }
   
   return self;
}

-(void) print
{
   NSLog(@"%f + %fi", self.real, self.imaginary );
}

@end

we are finishing the two classes .h and .m using protocol now we are importing these two classes into main method.

#import 



#import "Fraction.h"
#import "Complex.h"

int main(int argc, const char * argv[])
{

   @autoreleasepool {
       
       // insert code here...
       
       Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10];
       Complex *comp = [[Complex alloc] initWithReal: 5 andImaginary: 15];
       
       id <Printing> printable;
       
       // print it
       printable = frac;
       
       NSLog(@"The fraction is: " );
       
        [frac print];
       
        NSLog(@"\n");
       
       // print complex
       
       printable = comp;
       
       NSLog(@"The complex number is: " );
       
       [printable print];
       
        NSLog(@"\n");
       
   }
   return 0;
}

After importing the classes creating the objects for two classes and you can observe the above initWith is a class constructor type. we are assigning the vales

Numerator: 3 denominator: 10
Real: 5 andImaginary: 15

using class objects call the instance method i.e print (printing protocol method)

and we get the output as shown below.

2013-07-19 13:07:11.606 Protocols[1149:303] The fraction is:
2013-07-19 13:07:11.608 Protocols[1149:303] 3/10   
2013-07-19 13:07:11.613 Protocols[1149:303]
2013-07-19 13:07:11.614 Protocols[1149:303] The complex number is:
2013-07-19 13:07:11.614 Protocols[1149:303] 5.000000 + 15.000000i
2013-07-19 13:07:11.615 Protocols[1149:303]

this is the way of using protocols in our program, we can create multiple protocols and we can access multiple protocols in the class.

Protocols In The Real World

A more realistic use case can be seen in your everyday iOS application development. The entry point into any iOS app is an “application delegate” object that handles the major events in a program’s life cycle. Instead of forcing the delegate to inherit from any particular superclass, the UIKit Framework just makes you adopt a protocol:
@interface YourAppDelegate : UIResponder
As long as it responds to the methods defined byUIApplicationDelegate, you can use any object as your application delegate. Implementing the delegate design pattern through protocols instead of subclassing gives developers much more leeway when it comes to organizing their applications.


No comments:

Post a Comment