KVO的初级使用

KVO    KEY -Value_Observer 的缩写,键值观察者

用于观察一个对象的属性的变化,如果被观察的对象的属性发生变化则进行相应的动作

如,利用此模式可以设计股票股价的实时显示

第一步。给要观察的对象的属性添加

[boy addObserver:self forKeyPath:@"boyName" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];//|同时获取两个值|
    [girl addObserver:self forKeyPath:@"womenName" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    //只要属性发生改变就会触发下面的方法

其中boy和girl为2个对象,属性有name和age。

第二步,被观察者属性变化,利用button改变

-(void)buttonClick:(id)sender
{
    UIButton * button = (UIButton *)sender;
    if (button.tag == 100) {
        [boy setValue:@"赵又廷" forKey:@"boyName"];
    }else if(button.tag ==101){
        [girl setValue:@"高圆圆" forKey:@"womenName"];
    }
}

第三步,  //只要属性发生改变就会触发下面的方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //1、表示被观察的成员变量的名称
    //2、表示的是被观察的成员变量所属的对象指针
    //3、表示的是存放被观察的成员变量变化前和变化后的值(变化前的键old 后的时new)
    UILabel * boyLabel = (UILabel *)[self.view viewWithTag:100];
    UILabel * girlLabel = (UILabel *)[self.view viewWithTag:101];
    //判断对象是否
    if ([object isMemberOfClass:[Man class]]) {
        NSString * oldName = [change objectForKey:@"old"];
        NSString * newName = [change objectForKey:@"new"];
        NSString * allBoyName = [NSString stringWithFormat:@"%@-------%@",oldName,newName];
        boyLabel.text = allBoyName;
    }else if([object isMemberOfClass:[Women class]]){
        NSString * oldName = [change objectForKey:@"old"];
        NSString * newName = [change objectForKey:@"new"];
        NSString * allGirlName = [NSString stringWithFormat:@"%@--------%@",oldName,newName];
        girlLabel.text = allGirlName;
    }
}
 
原文地址:https://www.cnblogs.com/huoxingdeguoguo/p/4598511.html