Can somebody explain me how exactly does the delegate work in iphone sdk.....??? A simple example how to use the d开发者_运维问答elegate and what are the advantages of using delegate.
Delegate pattern is used widely in iPhone SDK. Consider the examples:
You are running an animation. The underlying system handles the animation for you. But it is natural that you want to do something when the animation is over (say, you want to activate a button or show some text when animation is over). Now how the animation system will know what to do when animation is over? After all this is your custom task. So you will configure a delegate for the animation and the system will call that delegate method when the animation is over. Obviously you will do your custom tasks in this delegate method.
You have a text field and you want to know when the user have tapped or edited something in the field. How you will know that? You will configure a delegate for your text field and predefined delegate method will be called by the UITextField class when that particular field is edited or tapped.
Forget UIApllicationDelegate? The system does the job of loading and running the app. How it will tell you that it's initialization have finished and you can now run your code? It will call applicationDidFinishLaunching method of your app delegate.
You are making an asynchronous http request. After loading the data, your delegate method will be called so that you can now work with the data.
There are many more examples. In order to use delegate, you will require to specify the delegate object and sometimes the selector also. What exactly is needed to be done is dependent on what are you doing. That is, configuring an animation delegate is different from configuring a text field delegate. But the general procedure is same, that is you need to specify your delegate object.
Example code for animation :
CATransition *animation = [CATransition animation]; [animation setDelegate:delegate]; // here delegate is your delegate object
After animation is over, your delegate object's
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flagwill be called and you will do your customization in this method.
Delegates are a way to decouple message senders and receivers. Rather than a message publisher having to #import
the definitions of all the classes that might have an interest in the message, The publisher instead defines a delegate type, and calls a method on that delegate in order to send messages. The receiver class then implements the delegate.
Wikipedia has both an explanation and examples :)
In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. It passes the buck, so to speak (technically, an Inversion of Responsibility). The helper object is called the delegate. The delegation pattern is one of the fundamental abstraction patterns that underlie other software patterns such as composition (also referred to as aggregation), mixins and aspects.
Basic definition : A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. more details
scenario (used in message passing) : Suppose object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action. This is how delegation works.
With the help of protocols we can achieve delegation in iOS. Here is the code :
ViewControllerA.h
#import <UIKit/UIKit.h>
@interface ViewControllerA : UIViewController
{
}
@end
ViewControllerA.m
#import "ViewControllerA.h"
#import "ViewControllerB.h"
@interface ViewControllerA ()<SimpleProtocol>
@end
@implementation ViewControllerA
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self performSelector:@selector(delegatingWorkToControllerB)withObject:nil afterDelay:3.0];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)delegatingWorkToControllerB{
ViewControllerB *vcB = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerB"];
vcB.delegate = self;
[self presentViewController:vcB animated:YES completion:^{
}];
}
#pragma mark - SimpleProtocol Delegate Method
-(void)updateStatus:(NSString*)status {
NSLog(@"%@",status);
}
@end
ViewControllerB.h
#import <UIKit/UIKit.h>
@protocol SimpleProtocol<NSObject>
-(void)updateStatus:(NSString*)status;
@end
@interface ViewControllerB : UIViewController
{
}
@property(nonatomic, unsafe_unretained)id<SimpleProtocol>delegate;
@end
ViewControllerB.m
#import "ViewControllerB.h"
@interface ViewControllerB ()
@end
@implementation ViewControllerB
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self performSelector:@selector(informingControllerAAfterCompletingWork) withObject:nil afterDelay:3.0];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)informingControllerAAfterCompletingWork{
//you can perform some task here and after completion of the task you can call this to notify the previous controller
[self.delegate updateStatus:@"controller B work has done.. update successfull :)"];
//dismissing the view controller
[self dismissViewControllerAnimated:YES completion:^{
}];
}
@end
Working Example : code
精彩评论