iOS代理的使用

来源:互联网 发布:淘宝千牛包邮怎么设置 编辑:程序博客网 时间:2024/05/29 13:29

代理的主要组成部分:

协议:声明委托方要代理方去处理什么事情;

委托对象:根据指定的协议,指定代理去完成什么功能;

代理对象:根据指定的协议,完成委托方需要实现的功能;

三者的关系如下图


协议委托代理三方的关系.png

可能看完这些概念还是会有些模糊。举个简单的例子有这样一个需求,控制器A跳转到控制器B,在B返回到A的时候,B的某些数据需要传递给A处理。这个时候B就是委托方,A就是代理方, B需要制定一个协议,协议中声明要处理数据的方法。然后A要成为B的代理,去实现协议中声明的方法。

使用代理实现界面间的传值(逆传):

创建委托界面B,代码如下:

.h文件

#import//新建一个协议,协议的名称一般是由:"类名+Delegate"@protocolViewControllerBDelegate//代理方必须实现的方法@required//代理方可选实现的方法@optional- (void)ViewControllerBsendValue:(NSString*)value;@end@interfaceViewControllerB:UIViewController//委托代理人,为了避免造成循环引用,代理一般需使用弱引用@property(weak,nonatomic)id delegate;@end

.m文件

#import"ViewControllerB.h"@interfaceViewControllerB()@property(weak,nonatomic)IBOutletUITextField*textField;@property(weak,nonatomic)IBOutletUIButton*btn;@end@implementationViewControllerB- (IBAction)btnClick:(id)sender {    [self.navigationController popViewControllerAnimated:YES];if([_delegate respondsToSelector:@selector(ViewControllerBsendValue:)])    {//如果协议响应了sendValue:方法//通知代理执行协议的方法[_delegate ViewControllerBsendValue:_textField.text];    }}

创建代理界面A:

.m文件

#import"ViewController.h"#import"ViewControllerB.h"@interfaceViewController()@end@implementationViewController- (void)viewDidLoad {    [superviewDidLoad];// Do any additional setup after loading the view, typically from a nib.}- (void)ViewControllerBsendValue:(NSString*)value{//创建一个警告框,来显示从B传过来的值UIAlertController* alerView = [UIAlertControlleralertControllerWithTitle:@"委托界面B传过来的值"message:value preferredStyle:UIAlertControllerStyleAlert];//给警告框添加按钮UIAlertAction*action = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction* _Nonnull action) {    }];    [alerView addAction:action];//弹出警告框[selfpresentViewController:alerView animated:YEScompletion:nil];}- (IBAction)segueBtn:(id)sender {}/**

*  跳转到B的时候调用

*  作用:设置A为B的代理

*/- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender{//设置跳转时的目标控制器ViewControllerB *vc = segue.destinationViewController;//设置A为B的代理vc.delegate =self;}@end

最终效果


代理逆传值演示.gif

根据上面这个例子,其实我们不难发现,代理其实就像是在委托方声明方法,然后由代理方去实现,从而达到传值的效果的。

总结:

使用代理的时候,一般发送数据的一方为委托方,需要接收数据并对数据进行处理的一方为代理方;

委托方需要定义一个协议,还要添加代理人属性,只有设置了委托方的代理人属性的类才可以成为委托方的代理;关键代码如下:

//新建一个协议,协议的名称一般是由:"类名+Delegate"@protocolViewControllerBDelegate@required//代理方必须实现的方法@optional//代理方可选实现的方法,//代理方法名称一般由:"类名+方法名"- (void)ViewControllerBsendValue:(NSString *)value;@end@interfaceViewControllerB: UIViewController//关键属性委托代理人,为了避免造成循环引用,代理一般需使用弱引用@property(weak,nonatomic) id delegate;@end

3.委托方通知代理方工作的代码(给代理方传值);

//新建一个协议,协议的名称一般是由:"类名+Delegate"@protocolViewControllerBDelegate@required//代理方必须实现的方法@optional//代理方可选实现的方法,//代理方法名称一般由:"类名+方法名"- (void)ViewControllerBsendValue:(NSString *)value;@end@interfaceViewControllerB: UIViewController//关键属性委托代理人,为了避免造成循环引用,代理一般需使用弱引用@property(weak,nonatomic) id delegate;@end

4.代理方需要设置自己成为委托方的代理,也是设置委托方的delegate属性为self,一般是在界面跳转的时候,取到委托方的控制器,并设置的。

原创粉丝点击