zoukankan      html  css  js  c++  java
  • KVO(键-值观察)

    // 1.键-值观察 
    // 2.它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。 
    // 3.符合KVC(Key-ValuedCoding)机制的对象才可以使用KVO 
    // 4.实现过程 
    // ①注册,指定被观察者 
    // ②实现回调方法 
    // ③移除观察

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
        // 实例化一个观察者对象
        self.stockForKVO = [[StockData alloc] init];
        // 初始化
        [self.stockForKVO setValue:@"searph" forKey:@"stockName"];// KVC
        [self.stockForKVO setValue:@"10.0" forKey:@"price"];// KVC
         
        // 监听并显示在 lable 里 - 注册观察者
        [self.stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew context:nil];
         
        self.myLable.textColor = [UIColor redColor];
        self.myLable.text = [self.stockForKVO valueForKey:@"price"];
         
        // 创建 button 按钮
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setFrame:CGRectMake(9015014042)];
        [button setTitle:@"按钮" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
     
    // button响应方法
    - (void)buttonAction
    {
        [self.stockForKVO setValue:@"20.0" forKey:@"price"];
    }
     
    // 回调方法
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if ([keyPath isEqualToString:@"price"])
        {
            self.myLable.text = [self.stockForKVO valueForKey:@"price"];
        }
    }
     
    - (void)dealloc
    {
        // 移除观察者
        [self.stockForKVO removeObserver:self forKeyPath:@"price"];
    }
  • 相关阅读:
    51Nod 2006 飞行员配对(二分图最大匹配)-匈牙利算法
    51Nod 1212无向图最小生成树
    51Nod 1081前缀和
    51Nod 1118 机器人走方格--求逆元
    Java四种线程池的使用
    java常用的几种线程池比较
    一名3年工作经验的程序员应该具备的技能(写得很好,果断转)
    《深入理解mybatis原理》 MyBatis的架构设计以及实例分析
    javadoc
    java 反射机制 观点
  • 原文地址:https://www.cnblogs.com/yangmx/p/3844949.html
Copyright © 2011-2022 走看看