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

Total Post:13

Posted on    February-26-2015 3:58 AM

 iPhone iPhone  Mobile Development  Ios 

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

Jeet Verma
Jeet Verma

Total Post:110

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


- (void) CountryAddedToList;


@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;




/// Code of AddCountry.m file

#import "AddCountry.h"

@implementation AddCountry

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


     _CountryList=[[NSMutableArray alloc]init];



    [_CountryList addObject:object];

    [_delegate CountryAddedToList];



// 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;


// code of view controller.m

- (void)viewDidLoad {

    [super viewDidLoad];

// initialization of addcountry class  object and setting delegate.

_CountryObj=[[AddCountry alloc]init];



- (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.


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



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

Follow MindStick