zoukankan      html  css  js  c++  java
  • IOS KVO & KVC 模式

    一.KVO 模式

    key-value observing (观察者模式),即键值监听,分为观察者和被观察对象,当被观察对象中属性发生变化,被观察对象会通过观察者.

    OC中,KVO常用方法:

    • 注册指定Key路径的监听器 : addObserver: forKeyPath: options: context: 
    • 删除指定Key路径的监听器 : removeObserver: forKeyPath ,removeObserver: forKeyPath: context:
    • 回调监听 : observerValueForKeyPath: ofObject: change: context: 

    KVO 使用步骤:

    • 通过 addObserver: forKeyPath: options: context: 为被观察对象(一般为数据模型),注册监听器
    • 重写监听器 observerValueForKeyPath: ofObject: change: context 方法
       1 // 被观察对象
       2 @interfance Account : NSObject
       3 
       4 @property (nonautomatic, assign) float balance;
       5 
       6 @end
       7 
       8 @implementation Account
       9 
      10 ...
      11 
      12 @end
      13 
      14 // 监听对象
      15 @interfance Person : UIViewController
      16 {
      17     float balance;
      18     Account *account;
      19 }
      20 
      21 - (Person *) initWithPerson;
      22 
      23 - (void) observerValueForKeyPath: (NSString *) forPath ofObject: (id) object change: (NSDictionary *) change context: (void *) context;
      24 
      25 @end
      26 
      27 @implementation Person
      28 
      29 - (Person *) initWithPerson
      30 {
      31     [self.account addObserver: self forKeyPath: @"balance" options: 0 context: @"KVO_ACCOUNT_BALANCE"];
      32 }
      33 
      34 - (void) observerValueForKeyPath: (NSString *)forPath foObject: (id) object change: (NSDictionary *) change context: (void *) context
      35 {
      36     if (context == @"KVO_ACCOUNT_BALANCE" && object == self.account)
      37     {
      38 
      39     }
      40 }
      41 
      42 @end

    二.KVC 模式

  • 相关阅读:
    Java中的final关键字
    使用chrome浏览器调试时的搜索技巧
    查看“文件路径”&“在此处打开命令窗口”
    python安装 错误 “User installations are disabled via policy on the machine”
    Charles 激活入口以及账号密码
    大数据学习(一) | 初识 Hadoop
    Django基础3-数据库交互
    Django基础2
    Django基础使用1
    创建-Django创建启动
  • 原文地址:https://www.cnblogs.com/naray/p/4546560.html
Copyright © 2011-2022 走看看