KVO(监听)

_g = [Dog new];
    _g.name = @"AAAA";
    
    //被监听的对象
    //监听者
    //被监听的属性(被监听的对象的属性)
    [_g addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
   
    NSLog(@"%@",change[@"old"]);
    NSLog(@"%@",change[@"new"]);
}
-(void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(void *)context{
    [_g removeObserver:self forKeyPath:@"name" context:nil];
}

也可以在-(void)dealloc{}方法中移出

猜你喜欢

转载自blog.csdn.net/qq_33656996/article/details/81774772
KVO