Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

iOS - Delegates (Delegates)

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

Create a Delegate Object

  1. Create a single view application

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

addNewFile

  1. Then select Objective C and click Next

  2. Name the subclass of SampleProtocol as NSObject, as follows

setProtocolName

  1. 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

  1. Drag a label from the object library to UIView to add a UILabel in ViewController.xib, as follows:

delegateLabel

  1. 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

  1. 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

  1. 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.

delegateResult