Monday, September 10, 2012

Defining a delegate protocol for a custom class and implementing it in Objective-C

Delegate is a protocol by which an object sends message to another object when an event is about to occur or has occurred. It is a way by which an implemented object callbacks an implementing object. To make it simple,  delegate enables number of objects to communicate with each other thus make coding more efficient. This simple post will show you an example how to define a delegate protocol and implement it.

There are two types of methods that can be defined in the delegate protocol:-
1. required: methods required to be implemented in the class of object which is assigned as the target for the delegate.
1. optional: methods which should be implemented in the class of target-object only if it needs to receive the messages.
Note: You can designate these methods using @required and @optional keywords

Let us create a custom class, subclass of UIView, named "CustomView" and its delegate protocol "CustomViewDelegate"

#import <UIKit/UIKit.h>

@protocol CustomViewDelegate <NSObject>
-(void) customViewDelegateMethod ;

@interface CustomView : UIView{

         id< CustomViewDelegate> delegate;


@property (strong, nonatomic) id<CustomViewDelegate> delegate;
In CustomView.h we have defined the delegate protocol "CustomViewDelegate" with an optional delegate method -(void) customViewDelegateMethod ; Inside the CustomView definition, a CustomViewDelegate object is created.

In CustomView.m synthesize the delegate object 
@ synthesize delegate;

Replace - (void) drawRect: (CGRect)rect{} with the code as show below
- (void)drawRect:(CGRect)rect{
    [self setBackgroundColor:[UIColor greyColor]];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 10, 100, 50);
    [button setTitle:@"Click Me!" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button_clicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
Here,  a background is set to grey color. An object of UIButton is created which is set to call a method button_clicked: when it is clicked. The button is then added as subview of the CustomView class.

Definition of button_clicked: method which is called when the button is clicked.
-(void)button_clicked:(id) sender{

    [delegate  customViewDelegateMethod];

Here, inside the method a delegate object calls its method which will invoke the class of object that has been assigned as the target for this delegate.

Now lets do the implementation of this class and its delegate

Create a UIViewController "YourViewController" (you can name it as you want) and in the header file  modify the code to look like this.
#import "CustomView.h"

@interface YourViewController : UIViewController<CustomViewDelegate>


Now in the YourViewController.m file in the viewDidLoad method include these lines.
CustomView *customView=[[CustomView alloc]initWithFrame:CGRectMake(10, 10, 300, 100)];
[self.view addSubview:customView];
Here, we created a CustomView object named customView and set its delegate to self (i.e. YourViewController). Then customView is added as the subView of YourViewController.

Finally, lets implemented the delegate method.

       NSLog(@"This message is sent to this YourViewController from CustomView object using its delegate protocal when the button was click there.");
      //Do your other stuffs

For this test, in the delegate method we just log a message in the console to notify that the delegate method has been called.

Now compile and run your code..... Huh! Are you kidding me? You dont even know how to compile your code? Ah just joking ... So if the above code works all fine you should see the log message in your Xcode console when you click the button.

Suggestions and corrections are most welcome. If you have any, please do so without hesitation.


  1. Great and really helpful article! Adding to the conversation, providing more information, or expressing a new point of view...Nice information and updates. Really i like it and everyday am visiting your site..

    iOS Training in Chennai

  2. Code referencing is an important skill that should be mastered by all programmers and I am glad that the author has taken the time to explain comprehensively the protocol for a custom class and implementing it in Objective-C. I will be trying out the suggested principles and then post my feedback. Meanwhile you can check out my article by clicking on How to Develop Good Research Writing Skills.