delegate设计模式
delegate设计模式
1.代理
三方:委托方、代理方、协议
2.定义协议
协议:一堆方法的声明(面试题)
#import <UIKit/UIKit.h> #warning 1.定义协议 @class TouchView; @protocol TouchViewDelegate <NSObject> @optional // touchView开始被点击 - (void)touchViewBeginTouched:(TouchView *)touchView; // touchView结束被点击 - (void)touchViewEndTouched:(TouchView *)touchView; @end @interface TouchView : UIView #warning 2.给外界提供设置Delegate属性的接口 // 在定义Delegate属性时,需要使用assign关键字,防止产生循环引用。 @property(nonatomic, assign)id<TouchViewDelegate>delegate; @end
#import "RootViewController.h" #import "TouchView.h" #warning 4.接受协议 @interface RootViewController () <TouchViewDelegate> @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. TouchView *touchView = [[TouchView alloc] initWithFrame:CGRectMake(130, 100, 100, 100)]; touchView.backgroundColor = [UIColor redColor]; #warning 3.给Delegate属性赋值 touchView.delegate = self; [self.view addSubview:touchView]; [touchView release]; } #warning 5.实现协议中的方法 #pragma mark - TouchViewDelegate - (void)touchViewBeginTouched:(TouchView *)touchView { self.view.backgroundColor = [UIColor greenColor]; } - (void)touchViewEndTouched:(TouchView *)touchView { touchView.backgroundColor = [UIColor colorWithRed:(arc4random() % 256 / 255.0) green:(arc4random() % 256 / 255.0) blue:(arc4random() % 256 / 255.0) alpha:1]; }
#import "TouchView.h" @implementation TouchView - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { #warning 6.在对应的时间点让Delegate去执行协议中对应的方法 if (_delegate && [_delegate respondsToSelector:@selector(touchViewBeginTouched:)]) // 判断协议存在,且方法被实现了 { [_delegate touchViewBeginTouched:self]; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if (_delegate && [_delegate respondsToSelector:@selector(touchViewEndTouched:)]) { [_delegate touchViewEndTouched:self]; } }