delegate設計模式

delegate設計模式面試

1.代理設計模式

三方:委託方、代理方、協議dom

 2.定義協議atom

協議:一堆方法的聲明(面試題)spa

#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];
    }
}
相關文章
相關標籤/搜索