美文网首页
delegate-代理设计模型-自定义

delegate-代理设计模型-自定义

作者: js_huh | 来源:发表于2020-07-23 18:55 被阅读0次

    delegate-代理的简单实现-自定义


    是什么?

    • 通过自定义代理的方式实现
      点击➕ / ➖ 实现对总价对应的更改!

    思路

    • delegate-代理的简单实现-自定义里面,
      因为在自定义Cell里面,设置了固定类型代理对象属性
      @property (nonatomic, weak)ViewController *delegate;
      所以存在这样的缺陷:
      • Cell和VC之间太紧密了,不利于后期扩展。
      • Cell依赖于VC,但如果需要使用其他VC时,用不了。
    • 有什么方法,让Cell和VC之间进行解耦 ?
      • 代理属性的固定类型,设置为id类型。
        虽然实现Cell和VC之间的解耦,但是id类型的代理属性,
        说明任何类型,都能成为代理对象,阿猫阿狗都可以,这样肯定不行.
    • 那么怎样才既能实现Cell和VC之间的解耦,又能够对代理对象做一些些约束 ?

    示例代码

    -- WineCell类 (委托方)
    -- 定义个内部协议,声明代理属性
    @class Wine;
    -- 内部协议
    @protocol WineCellDelegate<NSObject>
    -(void)plusTotal:(Wine *) wine;
    -(void)minusTotal:(Wine *) wine;
    @end
    
    @interface WineCell : UITableViewCell
    -- 代理属性
    @property (nonatomic, weak)id<WineCellDelegate> delegate;
    @end
    
    -- 点击➕ 按钮,调用代理方法
    @implementation WineCell
    - (IBAction)plusClick:(id)sender {
        ....
        if([self.delegate respondsToSelector:@selector(plusTotal:)]){
            [self.delegate plusTotal:self.wine];
        }
    }
    
    -- 代理方
    -- 遵循代理协议,
    @interface ViewController ()<WineCellDelegate> 
    @end
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
      WineCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
      cell.delegate = self; -- 设置代理对象
      return cell;
    }
    -- 实现代理方法
    -(void)plusTotal:(Wine *) wine { ........ }
    

    注意:

    • 委托方在调用代理协议的方法时,要判断代理方是否实现了此方法
      respondsToSelector:
      否则报错 NSInvalidArgumentException

    也可以看看


    来自于哪里?

    • iOS-MJ-UI基础-大神班/day-11/09-代理设计模式

    相关文章

      网友评论

          本文标题:delegate-代理设计模型-自定义

          本文链接:https://www.haomeiwen.com/subject/sudfkktx.html