Simple delegate tutorial for ios development

Hello everyone,

I’m writing this tutorial as an introduction to the delegate design pattern in IOS development. This tutorial is based around a very simple example I’ve put together as an iphone project.

As I was teaching myself iphone development I avoided properly learning using delegate functions other than getting a table view to work which was a real drag with my projects because creating custom delegate methods is a powerful tool that I should have been using all along.

Prerequisites for this tutorial are a basic understanding of UIKIt and communication between view controllers.

The example project which you can download at this link: Delegate Example Project

Purpose of this example: This example is a bare bones iphone project which contains two view controllers where the root viewcontroller (DelegateExampleViewcontroller) is meant to display a user entered number and a view controller which will be presented as a modal view controller (EnterAmountViewController) and the value entered by the user will be sent to the root view controller through a delegate method. Just running the project will explain better than I can in this paragraph.

Lets get started:

Open up EnterAmountViewController.h


//delegate to return amount entered by the user
@protocol EnterAmountDelegate 
@optional
-(void)amountEntered:(NSInteger)amount;

@end

This is the delegate declaration. For our delegate we only have one method which will be sending back to our root view controller an NSInteger which we will get from the user.

NOTE: we extend the protocal to be of type “NSObject” which helps with autocomplete

ALSO: the @optional qualifier means that any object which is declared to be a EnterAmountDelegate can implement that function but if the @required is used in its place xcode will require that the delegate implement that function.

@interface EnterAmountViewController : UIViewController {

    IBOutlet UITextField *amountTextField;

}

-(IBAction)cancelPressed;
-(IBAction)savePressed;

@property(nonatomic,assign)id delegate;

@end

As you can see we declare id which is a reference to the defined delegate. We need to declare this as a property so the root view controller can access it.

Next open up EnterAmountViewController.m and specifically look at this function:

-(IBAction)savePressed
{
    //Is anyone listening
    if([delegate respondsToSelector:@selector(amountEntered:)])
    {
        //send the delegate function with the amount entered by the user
        [delegate amountEntered:[amountTextField.text intValue]];
    }

    [self dismissModalViewControllerAnimated:YES];
}

This function is connected to the save button on the toolbar which would be when the user is done entering their number(which doesn’t really mean anything). This is the point where we’re gonna call the delegate function which we declared in the .h. Before we call the function we first check if anyone is listening with if([delegate respondsToSelector:@selector(amountEntered:)])

If someone is listening then we call amountEntered with the integer value of our text field.

Next open up DelegateExampleViewController.h

The one line to pay attention to is @interface DelegateExampleViewController : UIViewController {

where the the view controller is being declared as an “EnterAmountDelegate” which is saying that it will implement all required delegate functions and may implement some or all of the optional delegate functions. In our example we only have one optional delegate function.

Finally up DelegateExampleViewController.m

#pragma mark EnterNumbe Delegate function

//display the amount in the text field
-(void)amountEntered:(NSInteger)amount
{
    amountLabel.text = [NSString stringWithFormat:@"%i" , amount];
}

This is delegate function being implemented in our view controller. This function will be called from EnterAmountViewController and we know it will contain our user input which we care about. All we are doing is taking that value and displaying it as a string in our UILabel.

Thats it. In this tutorial we’ve gone over a basic example of using a delegate protocal to communicate between two view controllers. This probably could have been accomplished using notifications or another hacky method but by using delegates we have made the view controller much more reusable and organized.

I hope this tutorial has helped and if it has I would appreciate a comment or send me an email: Email Me

Again here is the sample iphone project. Delegate Example Project

-Ryan

You Are Your Own Gym

43 thoughts on “Simple delegate tutorial for ios development

  1. Rodrigo

    Great tutorial, I was struggling with delegation and now you have made it very easy to understand, thanks and please keep posting interesting iOS tutorials.

    Reply
    1. Ryan Post author

      No problem, I’m glad this helps. I wish I found something like this a little sooner when I didn’t really understand it.

      Reply
  2. scott.stephen.74@gmail.com

    Thanks for this tut.
    I have read a lot of different ones for delegates, but this one is the clearest and simplest of them all.
    Cheers

    Reply
  3. Anonymous

    Awesome Tutorial….this is the simplest one of all…Thanks for it..keep doing the great job man!!!!!

    Reply
  4. Pingback: How to pass value to a variable defined in parent class from child class? | PHP Developer Resource

  5. Surendra kunwar

    hello friends i am verry congused in deleget .h/.m file can i edit this files and if i edit thn when this editing possible

    Reply
  6. SparkyNZ

    Thanks so much for this. I have been scouring the internet, looking through loads of books an I couldn’t find a simple example of how all of this fits together until I read your example. Makes sense now.. I do find it uncomfortable having mention of a parent’s method inside the child’s interface .h file but I’m sure its something I can live with.. I just find Obj-C strange overall.. my fault from coming from Windows MFC background..

    Reply
  7. geenieWanted

    You are awesome! I have spent some hours just to understand the concept of custom delegate. You made it so simple! 5 stars for you Mr. Superstar!

    Reply
  8. David Smith

    A really good example.

    You create a delegate in your object to allow other objects to register to the delegate method(s). Which are callback methods. When the delegate processes data/info. it lets the registered objects that new data is ready.

    Reply
  9. KingCrawlerX

    Excellent explanation. So concise. All the books teach you is how to use provided delegates. Now my view controllers can talk to each other! And now I won’t have to abuse singletons and notificationCenter so much LOL again. Thanks so much and good work!

    Reply
  10. Roberto

    In this case what is the difference between a normal property variable (IBOutlet UITextField *amountTextField;) and this delegate implementation?! What are the advantages of using it?!

    Thanks for your tutorial!

    Reply
    1. admin Post author

      Well they are two separate things entirely. An IBOutlet is just the connection between your code implementation and Interface Builder. From an IBOutlet you can get a value from whatever you’re connecting to but a delegate implementation is more about events and having the parent in the relationship not have to worry about when to get a value or handle an event but just listen to it. I hope that makes sense.

      Reply
  11. Pingback: developer | Pearltrees

  12. Kostas

    Hey, thanks for the tutorial, it really helped me.

    But, I think the “id delegate;” declaration is not necessary,
    since you declare a property.
    If you comment it, it works pretty fine.

    Reply
    1. admin Post author

      You are right about not needing the declaration, this was older and I will clean it up. I’m glad it helped you out.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


3 - one =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>