Delegates Example
Suppose object A calls B to perform an operation. Once the operation is complete, object A must know that object B has finished the task and object A will perform other necessary operations.
The key concepts in the example above are
- A is B's delegate object
- B references an A
- A will implement B's delegate methods
- B notifies through delegate methods
Create a Delegate Object
-
Create a single view application
-
Then select File -> New -> File...

-
Then select Objective C and click Next
-
Name the subclass of SampleProtocol as NSObject, as follows

- Then select Create
6. Add a protocol to the SampleProtocol.h file, then update the code as follows:
#import
// Protocol definition
@protocol SampleProtocolDelegate
@required
- (void) processCompleted;
@end
// Protocol definition end
@interface SampleProtocol : NSObject
{
// Delegate to respond back
id _delegate;
}
@property (nonatomic,strong) id delegate;
-(void)startSampleProcess; // Instance method
@end
7. 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 follows:

- Create an IBOutlet label named myLabel, then update the code as shown below and display SampleProtocolDelegate in ViewController.h
#import
#import "SampleProtocol.h"
@interface ViewController : UIViewController
{
IBOutlet UILabel *myLabel;
}
@end
- Implement the delegate 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 output shown below; the initial label will also keep running, and once the delegate method is called by the SampleProtocol object, the label's running code will also update.
