YouTip LogoYouTip

Ios Delegates

Suppose object A calls object B to perform an operation, and once the operation is complete, object A must be notified that object B has finished its task, so that object A can carry out other necessary actions. The key concepts in the above example are: * A is the delegate of B * B holds a reference to A * A implements B’s delegate methods * B notifies A via delegate methods Creating a Delegate Object 1. Create a Single View Application 2. Then select File β†’ New β†’ File... ![Image 1: addNewFile](#) 3. Then select Objective-C and click Next 4. Name the subclass of SampleProtocol as NSObject, as shown below ![Image 2: setProtocolName](#) 5. Then click Create 6. Add a protocol to the SampleProtocol.h file and update the code as follows: ```objc #import // Protocol definition @protocol SampleProtocolDelegate @required - (void) processCompleted; @end // End of protocol definition @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 to implement the instance method: ```objc #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: ![Image 3: delegateLabel](#) 9. Create an IBOutlet for the label named `myLabel`, then update the code as shown below and declare `SampleProtocolDelegate` in ViewController.h: ```objc #import #import "SampleProtocol.h" @interface ViewController : UIViewController{ IBOutlet UILabel *myLabel; } @end 10. Implement the delegate method, create a `SampleProtocol` object, and call the `startSampleProcess` method. Update ViewController.m as shown below: ```objc #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { ; SampleProtocol *sampleProtocol = [init]; sampleProtocol.delegate = self; [myLabel setText:@"Processing..."]; ; // Do any additional setup after loading the view, typically from a nib. } - (void)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 shown below. Initially, the label displays β€œProcessing…”, and once the delegate method is invoked by the `SampleProtocol` object, the label’s text updates accordingly. ![Image 4: delegateResult](#)
← Ios UiIos Action Outlet β†’