KVO

来源:互联网 发布:淘宝怎么关联小号 编辑:程序博客网 时间:2024/06/07 20:18

//observer观察者  self.person被观察者

    //KVO 是基于KVC 实现的

    [self.personaddObserver:selfforKeyPath:@"name"options:NSKeyValueObservingOptionNewcontext:nil];


//观察者发现被观察者变化的时候 走这个方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    NSLog(@"%@",keyPath);

    NSLog(@"%@",object);

    NSLog(@"%@",change);



   //取值第一种方式

   id new = [object valueForKeyPath:keyPath];  //object取出观察对象  

    NSLog(@"%@",new);

   //取值第二种方式

    id new1 = [changeobjectForKey:NSKeyValueChangeNewKey];

    NSLog(@"new1---%@",new1);


}

button改变给被观察者赋值

- (IBAction)buttonAction:(UIButton *)sender {

    NSLog(@"button------%@",self.person.name);

    //只要对self.person.name赋值 就会走观察方法 不管所赋的值是否变化

    self.person.name =@"wyj";

}



0 0
原创粉丝点击