Home > DeveloperSection > Forums > What is protocol in iOS
Jennifer Morgan
Jennifer Morgan

Total Post:13

Points:95
Posted on    February-26-2015 3:58 AM

 iPhone iPhone  Mobile Development  Ios 
Ratings:


 1 Reply(s)
 711  View(s)
Rate this:
What is protocol in iOS?


Jeet Verma
Jeet Verma

Total Post:110

Points:776
Supported
Posted on    February-27-2015 3:04 AM

A protocol is a group of related properties and methods that can be implemented by any class.

 

Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation.

 

Lets understand this with the help of an example

 



// code of AddCountry.h file

#import <Foundation/Foundation.h>

 

// Protocol Name

@protocol AddCountryProtocolDelegate <NSObject>

// protocol method that called after country added in list

@required

- (void) CountryAddedToList;

@end

@interface AddCountry : NSObject

// hold country list.

@property (nonatomic, retain)NSMutableArray* CountryList;

// delegate object

@property (nonatomic,strong) id <AddCountryProtocolDelegate>delegate;

// method that add country to list

-(void)addCountryToList:(NSString *)object;

@end

 

 

/// Code of AddCountry.m file

#import "AddCountry.h"

@implementation AddCountry

-(void)addCountryToList:(NSString *)object{

    if(_CountryList==nil){

     _CountryList=[[NSMutableArray alloc]init];

 

    }

    [_CountryList addObject:object];

    [_delegate CountryAddedToList];

}

@end

// code of view controller.h

#import <UIKit/UIKit.h>

#import "AddCountry.h"

@interface ViewController : UIViewController<AddCountryProtocolDelegate>

- (IBAction)AddCountryButtonTap:(id)sender;

@property (strong, nonatomic) IBOutlet UITextField *TxtCountry;

@property(strong,nonatomic)AddCountry *CountryObj;

@end

// code of view controller.m

- (void)viewDidLoad {

    [super viewDidLoad];

// initialization of addcountry class  object and setting delegate.

_CountryObj=[[AddCountry alloc]init];

    _CountryObj.delegate=self;

}

- (IBAction)AddCountryButtonTap:(id)sender {

    [_CountryObj addCountryToList:_TxtCountry.text];

}

 

#pragma mark  add country class delegate method. this method is called after a country object added to list.

-(void)CountryAddedToList{

    NSLog(@Country added to the list.");

    _TxtCountry.text=nil;

}


Don't want to miss updates? Please click the below button!

Follow MindStick