以前看别人写有关委托代理之间的关系,一直搞不明白谁是委托谁是代理。今天突然顿悟了,赶紧写下来,希望也能帮助其他人,直接上代码。
第一个类,FirstViewController。
.h文件:
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface FirstViewController :UIViewController
<SecondViewDelegate>
{
SecondViewController* _second;
}
@property(nonatomic,retain)SecondViewController* second;
@end
- (IBAction)pressButton:(id)sender {
[self.navigationControllerpushViewController:_secondanimated:YES];
NSLog(@"press button");
}
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view from its nib.
_second = [[SecondViewControlleralloc]init];
_second.delegate =self;
}
#pragma mark delegate
-(void)passValue:(id)arg
{
NSLog(@"%@",arg);
}
#import <UIKit/UIKit.h>
@protocol SecondViewDelegate;
@interface SecondViewController :UIViewController
{
id<SecondViewDelegate>__unsafe_unretained _delegate;
}
@property(assign)id<SecondViewDelegate>delegate;
@end
@protocol SecondViewDelegate <NSObject>
-(void)passValue:(id)arg;
@end
.m文件- (IBAction)pressButton:(id)sender {
[self.navigationControllerpopViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view from its nib.
[self.delegate passValue:@"Just do it"];
}
- 以上代码实现的功能是:First的View上有一个按钮,在点击First push到 Second时, 执行passValue:方法,此时Second把参数"Just do it"传递过来,从而在First中打印出来。
- 所谓的委托代理就是,委托者“SecondViewController“委托它的代理者”FirstViewController“实现-(void)passValue:(id)arg;方法。此方法是在SceondViewController中声明的,但是要是FirstViewController中实现,所以SecondViewController就是委托者,FirstViewController就是代理者。并且达到传递参数的效果。
- 因为用的ARC模式所以要这样声明id<SecondViewDelegate>__unsafe_unretained _delegate; 不然会报错。
- 那么在First中怎么样控制passValue:方法什么时候执行呢。这个就要看[self.delegate passValue:@"Just do it"]在Second中哪个函数里了,等运行到包含[self.delegate passValue:@"Just do it"]时,First中passValue:就会执行。