delegate 模式
在OC的学习过程中,学习代理(delegate)是在学习类的扩展那里。UI中的delegate模式,典型的是UITextField,实现键盘回收。
完整的代理模式由 委托方,代理方 ,协议 组成。
委托方 声明代理变量
1.导入协议头文件
#import "MarryProtocol.h"
2.设置代理变量 :delegate 的类型若不确定则必须为id(泛型)类型。delegate后面必须以<代理名>接受代理,这样在委托类的.m中就可以直接使用delegate变量,并且 把delegate当做receiver ,来调用delegate中实现的协议的方法。
设置代理变量:
id <MarryProtocol>_husband;//delegate
让delegate实现协议中的方法:
- (void)clothDirty
{
[_husbandwashCloth];
}
1.协议创建的时在类的选择那里选择protocol,命名时规范XXXProtocol。协议仅有.h声明文件,仅有方法没有变量,方法的实现交给代理方去实现。方法有 可实现 @optional 和 必须实现 @required 两种。默认是必须实现的。
@protocol MarryProtocol <NSObject>
@required//默认是required,默认协议里方法是必须实现的。
- (void)doHouseWork;
@optional
- (void)takeCareBaby;
@end
@protocol RadionViewDelegate <NSObject>
// 默认必须实现
- (void)radioView:(RadionView *)radioView stopMusicButton:(NSInteger)playModel; //
- (void)radioView:(RadionView *)radioView frontMusicButton:(UIButton *)frontButton;
- (void)radioView:(RadionView *)radioView nextMusicButton:(UIButton *)nextButton;
@optional //选择实现
- (void)radioView:(RadionView *)radioView listMusicButton:(UIButton *)listButton;
- (void)radioView:(RadionView *)radioView downloadButton:(UIButton *)downloadButton;
@end
代理方的作用1是被委托方委托为代理,2.实现协议中的方法。
在手势识别中委托方是手势动作的被触碰者,如某个视图被轻拍了一下要改变颜色,代理方 视图控制器 接受颜色协议并且实现颜色改变方法。所以让 委托方某个视图 的颜色发生改变的是 代理方视图控制器。
1.引入协议头文件
#import "MarryProtocol.h"
2.尖括号接受代理
@interface Boy :NSObject <MarryProtocol>//若接受多个协议,可以写在同一个尖括号里面,协议以逗号隔开
3.实现代理中的方法- (void)washCloth
{
NSLog(@"程序员在洗衣服");
}
Target/Action 设计模式 ,在UI中UIButton 就是采用这个模式。
addTarget:(id)(target) action:@selector(acton) forControlEvents:(UIControlEvents..)
当 触发按钮的(UIControlEvents..)状态时,执行目标target的action方法。
因此为了让我们写的控件做到“高内聚低耦合”,实现更多的功能,更加开放。当自己写控件的时候就需要用到Target/Action 设计模式或者delegate 设计模式。
1.在自定义类的.h中声明 泛型类型的 target 和 SEL 类型的 action 变量
@interface TargetActionView :UIView
@property (nonatomic,assign)id target;
@property (nonatomic,assign)SEL action;
@end
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[_target performSelector:_actionwithObject:self];
}
3.delegate delegate执行的方法是固定方法(协议中的),target/action 执行的方法不确定。
delegate模式和 target/action模式 的相同点
1. 传递过去的方法参数都是self
2. 都不是自己执行方法