Progressing towards Innovation...

 

Using Delegates in Objective C

June 23, 2014by GLBADMIN53

Hi, I am Avinash Kashyap. I am an iOS programmer at Globussoft with 2 years of experience and have developed many games and apps on iOS viz. Sickipedia, Meditation Jar, Mot History etc. which could be found in App Store. Here I am going to share how to use the concept of communication between classes in Objective C by using ‘Delegates’.

‘Delegates’ is a powerful feature of Objective-C. During development of any Project and Application delegate plays very important role for passing message from one object to another. Delegation is a simple and clean way for connecting two Objects and helping them communicate with each other.

The idea behind delegate is that a Class A executes some code and after execution sends results to owner class. In order to facilitate this, Class A creates protocol which is called delegate.

Protocol has list of methods (without definition) and Class A has instance of protocol as a property (weak). Owner class implements definition of delegate methods of Class A and lastly during the creation of Class A sets its delegate property to owner Class.

Let’s try to understand the importance of Delegate through a real-time example:

We have two Objects one is a Team Manager(A) and another is Team Member(B). Team Manager is object who is responsible for managing all team members’ work and other office works. Manager(A) assigns some task to a Team Member(B) now since team manager has lots of other works so he won’t be able to watch over things, but Manager(A) wants to know task completion time taken by Team Member(B) for completing that task.

 

This is where delegate comes into action, Team Manager can use the delegate of Team Member to know completion time. When that Team Member(B) completes that task “Team Member Delegate” method sends task completion message to Team Manager and Team Member can calculate the task completion time.

Here is the Code example of Delegation:

I created a class TaskViewController, in this class I will declare custom delegate method , this custom delegate method sends message to owner about the completion.

#import <UIKit/UIKit.h>
@protocol TaskViewControllerDelegate;
@interface TaskViewController : UIViewController
@property (nonatomic, weak) id <TaskViewControllerDelegate> delegate;//instance of protocol
@property (nonatomic, strong) NSString *taskString;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;
@end

//Define Delegate
@protocol TaskViewControllerDelegate <NSObject>

//Delegate Method
-(void) taskViewController:(TaskViewController *)taskViewController taskCompletionUpdate:(NSString *)taskUpdated;
@end

@implementation TaskViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //Add a UIImageView as a SubView of View
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 300)];
    [self.view addSubview:self.imageView];
    //Add UIActivityIndicator
    self.activityIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(140, 350,    40, 40)];
    [self.activityIndicator setBackgroundColor:[UIColor clearColor]];
    [self.activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:self.activityIndicator];
    [self.activityIndicator startAnimating];
    //Send Message to Start Task
    [self performSelector:@selector(task) withObject:nil afterDelay:5.0];
}

//Method for perform Task
-(void) task{
    NSString *urlString = @"http://images.wallstcheatsheet.com/wp-content/uploads/2012/06/apple-logo-300x300.jpg";
    NSData *responseDate = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]];
    UIImage *image = [UIImage imageWithData:responseDate];
    [self.activityIndicator stopAnimating];
    self.imageView.image = image;
    // Check delegate
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(taskViewController:taskCompletionUpdate:)]) {
        //Send Message To Delegate
        [self.delegate taskViewController:self taskCompletionUpdate:@"Completed"];
    }
}

ViewController is another class, which is Owner of TaskViewViewController

Now I’m going to implement TaskViewControllerDelegate inside ViewController.

#import <UIKit/UIKit.h>
#import "TeamMemberViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController : UIViewController <TeamMemberDelegate>
@property (nonatomic, weak) UIButton *btn;
@end

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // Adding a UIButton as SubView of ViewController View.
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn.frame = CGRectMake(100, 200, 120, 40);
    self.btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.btn.layer.borderWidth = 1.0f;
    self.btn.layer.cornerRadius = 7.0f;
    self.btn.clipsToBounds = YES;
    [self.btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btn setTitle:@"Task" forState:UIControlStateNormal];
    [self.btn addTarget:self action:@selector(assignTaskButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];
}

// With to Task View Controller

-(void) assignTaskButtonClicked:(id)sender{

TeamMemberViewController *teamMemberView = [[TeamMemberViewController alloc] initWithNibName:@"TeamMemberViewController" bundle:nil];
taskString = @"Task";
delegate = self;// set Delegate to send message

[self presentViewController:teamMemberView animated:YES completion:nil];

}

#pragma mark -

#pragma mark Team Member Delegate Method

//Define Delegate Method of TeamViewController of receiving message after task completion

-(void) teamMemberController:(TeamMemberViewController *)teamMember taskCompletionUpdate:(NSString *)taskUpdated{

NSLog(@"Task Update Status == %@", taskUpdated);

}

@end

So you see how objects can communicate amounts themselves between objects and pass required data to the owner class after completion of specific task. We have aptly used such a system in apps like sikipedia, battersaver reborn, ninnimix etc.

Thanks for reading. Keep watching this space for more.

GLBADMIN

ss