Delegates Example
Suppose object A calls B to perform an operation. Once the operation is completed, object A must know 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 B's delegate object
- B holds a reference to A
- A will implement B's delegate methods
- B notifies through the delegate method
Creating a Delegate Object
1. Create a Single View Application
2. Then select File -> New -> File...

3. Then choose Objective-C and click Next
4. Name the subclass of NSObject as SampleProtocol, as shown below

5. Then click Create
6. Add a protocol to the SampleProtocol.h file, then update the code as shown below:
#import <Foundation/Foundation.h>
// 协议定义
@protocol SampleProtocolDelegate <NSObject>
@required
- (void) processCompleted;
@end
// 协议定义结束
@interface SampleProtocol : NSObject
{
// Delegate to respond back
id <SampleProtocolDelegate> _delegate;
}
@property (nonatomic,strong) id delegate;
-(void)startSampleProcess; // Instance method
@end7. 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
8. Drag a label from the Object Library onto the UIView to add a UILabel in ViewController.xib, as shown below:
9. Create an IBOutlet label and name it myLabel, then update the code as shown below and declare SampleProtocolDelegate in ViewController.h
#import <UIKit/UIKit.h>
#import "SampleProtocol.h"
@interface ViewController : UIViewController<SampleProtocolDelegate>
{
IBOutlet UILabel *myLabel;
}
@end
10. Implement the delegate methods, create an object for SampleProtocol, and call the startSampleProcess method. Update the ViewController.m file as shown below.
#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
11. You will see the output as shown below. The initial label will continue to run, and once the delegate method is called by the SampleProtocol object, the code that runs the label will also be updated.