Delegate Example
Suppose object A calls B to perform an operation, and once the operation is completed, object A must be aware that object B has finished the task and object A will perform other necessary operations.
The key concepts in the above example are:
- A is the delegate object of B
- B references A
- A will implement B's delegate method
- B notifies through the delegate method
Creating a Delegate Object
- Create a single view application
- Then select File -> New -> File...
- Then select Objective-C and click Next
- Name the subclass of NSObject as SampleProtocol, as shown below
- Then select Create
Add a protocol to the SampleProtocol.h file and update the code as follows:
#import <Foundation/Foundation.h> // Protocol definition @protocol SampleProtocolDelegate <NSObject> @required - (void) processCompleted; @end // End of protocol definition @interface SampleProtocol : NSObject { // Delegate to respond back id <SampleProtocolDelegate> _delegate; } @property (nonatomic,strong) id delegate; -(void)startSampleProcess; // Instance method @end
Modify the SampleProtocol.m file code to implement the instance method:
#import "SampleProtocol.h" @implementation SampleProtocol -(void)startSampleProcess{ [NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate selector:@selector(processCompleted) userInfo:nil repeats:NO]; } @end
Drag a label from the object library to UIView to add a UILabel in ViewController.xib, as shown below:
Create an IBOutlet label named myLabel, then update the code as shown below and display SampleProtocolDelegate in ViewController.h
#import <UIKit/UIKit.h> #import "SampleProtocol.h" @interface ViewController : UIViewController<SampleProtocolDelegate> { IBOutlet UILabel *myLabel; } @end
Complete the authorization method, create an object for SampleProtocol, and call the startSampleProcess method. Update the ViewController.m file 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
You will see the following output, the initial label will continue to run, and once the authorization method is called by the SampleProtocol object, the label's running code will be updated.