example for delegate
let's assume an object a calls an object b to perform an action. once the action is complete, object a should know that b has completed the task and take necessary action. this is achieved with the help of delegates.
the key concepts in the above example are −
a is a delegate object of b.
b will have a reference of a.
a will implement the delegate methods of b.
b will notify a through the delegate methods.
steps in creating a delegate
step 1 − first, create a single view application.
step 2 − then select file → new → file...
step 3 − then select objective c class and click next.
step 4 − give a name to the class, say, sampleprotocol with subclass as nsobject as shown below.
step 5 − then select create.
step 6 − add a protocol to the sampleprotocol.h file and the updated code is as follows −
#import <foundation/foundation.h>
// protocol definition starts here
@protocol sampleprotocoldelegate <nsobject>
@required
- (void) processcompleted;
@end
// protocol definition ends here
@interface sampleprotocol : nsobject {
// delegate to respond back
id <sampleprotocoldelegate> _delegate;
}
@property (nonatomic,strong) id delegate;
-(void)startsampleprocess; // instance method
@end
step 7 − implement the instance method by updating the sampleprotocol.m file as shown below.
#import "sampleprotocol.h"
@implementation sampleprotocol
-(void)startsampleprocess {
[nstimer scheduledtimerwithtimeinterval:3.0 target:self.delegate
selector:@selector(processcompleted) userinfo:nil repeats:no];
}
@end
step 8 − add a uilabel in the viewcontroller.xib by dragging the label from the object library to uiview as shown below.
step 9 − create an iboutlet for the label and name it as mylabel and update the code as follows to adopt sampleprotocoldelegate in viewcontroller.h.
#import <uikit/uikit.h>
#import "sampleprotocol.h"
@interface viewcontroller : uiviewcontroller<sampleprotocoldelegate> {
iboutlet uilabel *mylabel;
}
@end
step 10 implement the delegate method, create object for sampleprotocol and call the startsampleprocess method. the updated viewcontroller.m file is as follows −
#import "viewcontroller.h"
@interface viewcontroller ()
@end
@implementation viewcontroller
- (void)viewdidload {
[super viewdidload];
sampleprotocol *sampleprotocol = [[sampleprotocol alloc]init];
sampleprotocol.delegate = self;
[mylabel settext:@"processing..."];
[sampleprotocol startsampleprocess];
// do any additional setup after loading the view, typically from a nib.
}
- (void)didreceivememorywarning {
[super didreceivememorywarning];
// dispose of any resources that can be recreated.
}
#pragma mark - sample protocol delegate
-(void)processcompleted {
[mylabel settext:@"process completed"];
}
@end
step 11 we will see an output as follows. initially the label displays "processing...", which gets updated once the delegate method is called by the sampleprotocol object.