What is protocol in iOS

Total Post:13

 1805  View(s)
Rate this:
What is protocol in iOS?
  1. Post:110

    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


    - (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.");



      Modified On Apr-09-2018 01:47:09 AM


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.