day11-购物车05-通知的应用

购物车01-搭建基本骨架
购物车02-圆角按钮处理
购物车03-显示数据
购物车04-加号减号点击处理

NSNotification - 通知
NSNotificationCenter - 通知中心
模拟通知


是什么?

思路:

  • 为什么点击➕/➖无法改变"总价" ?
    ➕,➖ 在自定义cell里面, "总价"在VC里面
    自定义cell内部,无法拿到VC(控制器)里面的"总价"
  • 如何让自定义cell,拿到VC里面的"总价"?
    • 通知, 代理, KVO 三种方式。
  • 怎么使用通知,来实现改变总价?
    • 点击➕ 按钮时,发出个'通知'
      (Cell里面,发布通知的不同方式: 带userInfo和不带userInfo)
      - (IBAction)plusClick:(id)sender {
      [[NSNotificationCenter defaultCenter]postNotificationName:@"plusNotice" object:nil userInfo:@{@"wine": self.wine}];
      [[NSNotificationCenter defaultCenter]postNotificationName:@"buttonNotice" object: self];
      }
      
    • 在VC中,接收此'通知',改变'总价'
      • "监听通知"写在哪里,需要什么前提呢?
        • 监听通知一定写在"通知发布之前"
        • 监听通知只需要"监听一次"
      • 为什么在 viewDidLoad里面写监听通知 ?
        viewDidLoad初始化界面
        • viewDidLoad方法的特性,在控制器加载完毕后,只调用一次
        • viewDidLoad方法的调用为什么'一定是在通知发布之前呢'?
          • viewDidLoad方法没执行完,是不会存在界面得.
          • 点击➕ 按钮的时候,才发布通知
          • 界面都不存在,怎么会有➕ 按钮。
          • 所以viewDidLoad方法一定是在通知发布之前
      - (void)viewDidLoad {
      //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeTotal:) name:@"plusNotice" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeTotal:) name:@"buttonNotice" object:nil];
       }
      
      -(void)changeTotal:(NSNotification *) notice {
      NSDictionary * dict = notice.userInfo;
      Wine * wine =  dict[@"wine"];
      int total = wine.money.intValue * wine.count;
      self.totalLabel.text = [NSString stringWithFormat:@"%d",total];
      }
      
      -(void)changeTotal:(NSNotification *) notice {
      WineCell* wineCell = notice.object;
      Wine * wine = wineCell.wine;
      int total = wine.money.intValue * wine.count;
      self.totalLabel.text = [NSString stringWithFormat:@"%d",total];
      }
      

好处

  • VC 能够监听Cell的方法
  • 自定义Cell不依赖于VC
  • 解除了Cell和当前VC的耦合度 -- 解耦
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。