KVO(键-值观察)

时间:2023-03-09 18:06:36
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"];
}