oc中的代理模式

代理模式

如何实现代理者模式

  1. 需要被代理的类在接口定义@interface中定义自己的协议

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // xxx.h 
    @protocol MyTabbarDelegate <NSObject>
    // 定义代理者需要实现的方法集合
    - (void)onClick:(MyTabbar *)mytabbar clickIndex: (NSInteger) index;

    @end
    // 类
    @interface MyTabbar : UIView

    @property (strong, nonatomic) NSArray *tabs;
    @property (nonatomic, strong) MyButton *lastSelectBtn;
    // 定义代理属性
    @property (nonatomic, weak) id<MyTabbarDelegate> delegate;
    @end
  2. 在被代理的类中触发代理 对应的事件信号

    1
    2
    3
    4
    // 如果代理者 实现了对应的方法
    if ([self.delegate respondsToSelector:@selector(onClick:clickIndex:)]) {
    [self.delegate onClick:self clickIndex:button.tag];
    }
  3. 代理者类设置要实现的协议,并且实现对应的方法

    1
    2
    3
    4
    5
    6
    7
    8
    @interface TabViewController ()<MyTabbarDelegate>

    @end

    // 实现协议方法
    - (void)onClick:(MyTabbar *)mytabbar clickIndex:(NSInteger)index {
    NSLog(@"cur index is %ld", (long)index);
    }
文章作者: webaifei
文章链接: http://yoursite.com/2019/08/21/objective-c-daili/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 个人博客