• 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"];
    }
  • 相关阅读:
    LINQ查询操作符之First、FirstOrDefault、Last、LastOrDefault、ElementAt、ElementAtOrDefault、Contains、Any、All、Coun
    .Net 使用的快捷键
    P2073 送花
    洛谷P1514 引水入城
    花园
    八数码难题
    并查集题目整理
    树链剖分(强势借鉴)
    模拟题
    考试整理
  • 原文地址:https://www.cnblogs.com/yangmx/p/3844949.html
Copyright © 2020-2023  润新知