委托方 = 老板
代理方 = 员工
协议 = 合同bash
委托方传递信息或者事件到代理方,代理方执行相关操做。ui
翻译:老板把工做材料和工做内容交给员工,员工去干活。atom
委托方声明协议,并持有委托对象属性,调用代理方执行操做。spa
翻译:
1. 老板提供合同
2. 员工签名
3. 老板在他的公司里加上这号人
4. 老板分配工做
5. 员工干活翻译
MyView.h
//委托方声明协议
@protocol MyViewDelegate <NSObject>
//可选实现方法
@optional
-(void)optionalFunc;
//必须实现方法
@required
-(void)requiredFunc;
@end
复制代码
MyViewController.m
//代理方遵照协议
@interface MyViewController () <MyViewDelegate>
@property(nonatomic,strong)MyView * myView;
@end
复制代码
MyView.h
//委托方声明代理属性 注意要用weak修饰
@interface MyView : UIView
@property(nonatomic,weak)id<MyViewDelegate> delegate;
@end
复制代码
MyViewController.m
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.myView];
}
-(MyView *)myView{
if (!_myView) {
_myView = [[MyView alloc] initWithFrame:self.view.bounds];
_myView.backgroundColor = [UIColor whiteColor];
//持有代理
_myView.delegate = self;
}
return _myView;
}
@end
复制代码
MyView.m
//调用代理 调用前判断是否有方法实现
if ([self.delegate respondsToSelector:@selector(requiredFunc)]) {
[self.delegate requiredFunc];
}
复制代码
MyViewController.m
//实现协议方法
- (void)requiredFunc{
NSLog(@"requiredFunc");
}
复制代码