代理的目的是改变或传递控制链。允许一个类在某些特定时刻通知到其他类,而不需要获取到那些类的指针。可以减少框架复杂度。?另外一点,代理可以理解为java中的回调监听机制的一种类似
优点:1、避免子类化带来的过多的子类以及子类与父类的耦合
2、通过委托传递消息机制实现分层解耦
通过在A界面输入一段字符,在B界面的Label中显示的例子来说明
1.首先在A界面定义协议与方法
#import <UIKit/UIKit.h> //定义协议与方法 @protocol viewDelegate <NSObject> -(void)passText:(NSString *)text;
@end @interface ViewController : UIViewController //定义一个委托变量 @property(nonatomic,weak)id<viewDelegate>delagate; @end
2.A界面的实现文件
#import "ViewController.h" #import "ViewController1.h" @interface ViewController () @property(nonatomic,strong)UITextField *fid; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; button.backgroundColor = [UIColor redColor]; [button addTarget:self action:@selector(Click) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; _fid = [[UITextField alloc]initWithFrame:CGRectMake(100, 300, 100, 100)]; _fid.backgroundColor = [UIColor yellowColor]; [self.view addSubview:_fid]; } //点击事件 -(void)Click { ViewController1 *view = [[ViewController1 alloc]init]; self.delagate = view; [self.delagate passText:_fid.text]; [self.navigationController pushViewController:view animated:YES]; }
3.到了B界面的头文件
#import <UIKit/UIKit.h> #import "ViewController.h" //添加代理 @interface ViewController1 : UIViewController<viewDelegate> @end
4.B界面的实现文件
#import "ViewController1.h" @interface ViewController1 () @property(nonatomic,strong)UITextField *field; @end @implementation ViewController1 //实现代理方法 -(void)passText:(NSString *)text { [self.view setBackgroundColor:[UIColor whiteColor]]; _field = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; _field.backgroundColor = [UIColor redColor]; [self.view addSubview:_field]; //传值 _field.text = text; }
然后运行输入-跳转-显示,就行了
原文:http://www.cnblogs.com/asamu/p/5300335.html