iOS-设计模式之代理反向传值
2015-12-05 09:13
477 查看
代理设计模式就是自己的方法自己不实现,让代理对象去实现。
可以让多个类实现一组方法。
委托模式的好处在于:
1、避免子类化带来的过多的子类以及子类与父类的耦合
2、通过委托传递消息机制实现分层解耦
代理模式需要注意的地方时设置代理属性的时候不要用strong,而要assigne,或者weak这样可以避免循环引用。
具体实现过程:
在需要传值的类中申明协议,设置属性。
在实现的类中实现代理:
本文GitHub地址https://github.com/zhangkiwi/iOS_SN_delegate
可以让多个类实现一组方法。
委托模式的好处在于:
1、避免子类化带来的过多的子类以及子类与父类的耦合
2、通过委托传递消息机制实现分层解耦
代理模式需要注意的地方时设置代理属性的时候不要用strong,而要assigne,或者weak这样可以避免循环引用。
具体实现过程:
在需要传值的类中申明协议,设置属性。
// SecondViewController.h #import <UIKit/UIKit.h> @protocol delegateName <NSObject> - (void)sendData:(NSString *)string; @end @interface SecondViewController : UIViewController @property (nonatomic, assign)id<delegateName> delegate; @end // SecondViewController.m - (IBAction)actionOne:(id)sender { // 安全判断,是否实现了sendData:方法 if ([self.delegate respondsToSelector:@selector(sendData:)]) { [self.delegate sendData:self.textfile.text]; } [self dismissViewControllerAnimated:YES completion:nil]; }
在实现的类中实现代理:
// ViewController.m #import "ViewController.h" #import "SecondViewController.h" @interface ViewController ()<delegateName> @property (weak, nonatomic) IBOutlet UILabel *lable; @property (strong, nonatomic)SecondViewController *secondVC; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.secondVC = [[SecondViewController alloc]init]; // 设置代理对象 self.secondVC.delegate = self; } - (void)sendData:(NSString *)string{ self.lable.text = string; }
本文GitHub地址https://github.com/zhangkiwi/iOS_SN_delegate
相关文章推荐
- 关于oc中得import和include引用方法
- iOS 添加 Watch OS 1 应用后无法运行 An error was encountered while running (Domain = LaunchServicesError, Code = 0)
- nagios安装配置
- iOS7以上图片模糊效果
- iOS之github第三方框架(持续更新)
- Nagios:企业级系统监控方案
- 界面没有数据的情况下,添加默认图。
- 分清iOS中的OC和CF概念
- ios 获取相机权限
- iOS Json解析框架之MJExtension使用详解
- 用CocoaPods做iOS程序的依赖管理
- iOS开发CoreAnimation解读之四——Layer层动画内容
- IOS关闭虚拟键盘的几种方法
- iOS证书详解--再转
- 有感 iOS 应用间通讯 - 空中投放和自定义 Schema
- 蓝懿 iOS 技术交流和心得分享12.4
- IOS 拼接参数与URL
- xcode中设置ios9应用程序图标和启动图
- (NO.00004)iOS实现打砖块游戏(十五):导弹发射道具的实现(上)
- (NO.00004)iOS实现打砖块游戏(十五):导弹发射道具的实现(上)