代理传值(回调传值)
2016-03-23 17:56
453 查看
代理传值(回调传值)
1.代理又叫委托,是一种设计模式,代理是对象与对象之间的通信交互,代理解除了对象之间的耦合性。2.改变或传递控制链。允许一个类在某些特定时间通知到其他类
3.代理的属性常用assign的原因是:防止循环引用,导致对象无法正确释放
代理是一种回调机制,是一对一得关系,通知是一对多,代理效率比通知高。
代理传值使用如下
一、在输入值的类的.h文件中声明一个到代理,并声明一个代理方法; #import <UIKit/UIKit.h> //声明一个AViewControllerDelegate 协议 @protocol AViewControllerDelegate <NSObject> //@optional 为可选方法,如果不写则默认为必写方法 @optional //声明代理方法 -(void)transValue:(NSString *)string; @end @interface AViewController : UIViewController //找一个代理,并将其声明为属性 @property(nonatomic,assign)id<AViewControllerDelegate>delegate; @end 二、在需要传值的页面的类的.m文件实现切换到输入值的页面,并实现传值方法 #import "ViewController.h" //导入输入值的页面 #import "AViewController.h" //遵守协议 @interface ViewController ()<AViewControllerDelegate> //实现点击按钮切换页面 - (IBAction)push:(id)sender { UIStoryboard *storyboard=[UIStoryboard storyboardWithName:@"Main" bundle:nil]; AViewController *aViewController = [storyboard instantiateViewControllerWithIdentifier:@"AViewController"]; aViewController.delegata = self; [self presentViewController:aViewController animated:YES completion:^{ }]; } //实现传值方法 -(void)transValue:(NSString *)string{ self.lable.text = string; } @end 三、在输入值的页面的.m文件实现点击按钮回到原页面,并传值 //实现点击按钮回原页面,并传值的方法 - (IBAction)pop:(id)sender { //判断delegate是否存在,以及是否遵守协议 if (self.delegata && [self.delegata conformsToProtocol:@protocol(AViewControllerDelegate)]) { [self.delegata transValue:self.textField.text]; } [self dismissViewControllerAnimated:YES completion:^{ }]; } @end
相关文章推荐
- apache 访问日志如何设置每日新增一个日志文件、如何限制大小、设置记录内容
- word-spacing汉字不起作用的解决方法
- linux下screen工具的简单使用
- java监控函数执行时间
- infopath发布的提示“无法解析SOAP消息”(The SOAP message cannot be parsed)问题解决方案
- tomcat 设置项目 密码登陆
- twisted介绍
- 购物车的设计
- Swift 引入第三方字体库
- express的多重页面渲染问题
- textField 限制2位小数,编辑时不让键盘挡住
- 学习 shell脚本之前的基础知识
- js去掉字符串第一位与最后一位
- 领域驱动(DD)目录
- IOS之Objective-C学习 工厂模式
- selenium 学习笔记 ---新手学习记录(10) 问题总结(java)--poi--excel 操作
- this 指针
- 自定义textview旋转文字
- 文件传输导致PHP-smarty白屏故障
- 初见swift--基本类型