iOS-Delegates


Delegates Example

Suppose object A calls B to perform an operation. Once the operation is completed, object A must know that object B has completed 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 refers to A
  • A will implement B's Delegate method
  • B Notifies through the delegate method

Create a delegate (Delegates) object

1. Create a single-view application

2. Then select the file File -> New -> File...

addNewFile

3. Then select Objective C and click Next

4. Name the subclass of SampleProtocol NSObject as shown below

setProtocolName

5. Then select Create

6. Add a method to the SampleProtocol.h folder protocol, and then update the code as follows:

#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@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

8. Drag the label from the object library to the UIView, thus Add UILabel in ViewController.xib as shown below:

delegateLabel

9. Create an IBOutlet label and name it myLabel, then update the code as shown below and add it in ViewController.h SampleProtocolDelegate

#import <UIKit/UIKit.h>#import "SampleProtocol.h"@interface ViewController : UIViewController<SampleProtocolDelegate>{    IBOutlet UILabel *myLabel;}@end

10 is displayed. Complete the authorization method, 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 original tag will continue to run. Once the authorization method is called by the SampleProtocol object, the tag runs the program code. Will also be updated.

delegateResult