This tutorial will show you the simplest way to make delegate method to pass data from one class to another. You will see how these methods are called and how to get the selected value.

Suppose you have a class a class CountryViewController and there is a UITableView in it containing countries names and you want to set the selected country (didSelectRowAtIndexPath) name as text of a UITextFeild in RegisterViewController class.

In this case your child class would be CountryVC because it’s being used as a secondary class and similarly parent will be RegisterVC.

Open CountryViewController.h and after the #import statements add @protocol CountryVCDelegate; then after @interface add @property (weak) id<CountryVCDelegate> delegate; then where @interface @end add @protocol CountryVCDelegate <NSObject> after that you can add @required and from the next line you can add as many method as you like for a class that have extended to this delegate method must code. In our case we only need one method to give us the country name of the selected cell. So add -(void)getCountryName:(NSString*)country; So you finally header file will look like this:

and ofcourse after @required methods ends add @end
Now open CountryViewController.m. As this si the class which will return us the value of selected cell. So scroll down to didSelectRowAtIndexPath method and here add [self.delegate getCountryName:allCountriesNames[indexPath.row]];
Now open RegisterViewController.h and #import “CountriesViewController.h” and add <CountryVCDelegate>. That’s it for this class. You can add more functionality as per your requirement.
Now open RegisterViewController.m and add this CountriesViewController *ivc = [self.storyboard instantiateViewControllerWithIdentifier:@”CountryVC”];
            ivc.delegate = self; in viewDidLoad or where ever you need.
After that write the delegate method as:
    self.countryFeild.text = country;
As you can see we are setting text field text as the nsstring from other class. Run the code it’ll work great.
Tags : delegate methoddelegate method in objective cmake delegate method
Chaudhary Talha

The author Chaudhary Talha

I'm an iOS developer by profession and UI/UX designer by passion. All my tutorials are based on my personal experiences and whenever I learn something new I share it with the world.