WHAT IS PROTOCOL IN IOS

Jennifer Morgan

Total Post:13

Points:95
Posted by  Jennifer Morgan
 1159  View(s)
Ratings:
Rate this:
What is protocol in iOS?
  1. Jeet Verma

    Post:110

    Points:776
    Re: What is protocol in iOS

    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;

    }

Answer

NEWSLETTER

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