- (void) observeValueForKeyPath:(NSString *)keyPath (觀察的屬性)
ofObject:(id)object (被觀察者)
change:(NSDictionary<NSString *,id> *)change (值得變化)
context:(void *)context
[sta addObserver:p //觀察者
forKeyPath:@"count" //需要觀察的屬性
options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew //新舊值
context:nil];
3、兩個監聽者:
[_child addObserver:self
forKeyPath:@"myRoad"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil ];
// 監聽hungry值
[_child addObserver:self
forKeyPath:@"hungry"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionNew
context:nil ];
if ([keyPath isEqualToString:@"myRoad"]) {
//b) 取得新值的變化
NSNumber *num = [change objectForKey:@"new"];
NSInteger myRoad = [num integerValue];
//c) 做判斷
if (myRoad < 100) {
[self bautiful];
}
} else if ([keyPath isEqualToString:@"hungry"]) {
//d) 取得新值得變化
NSNumber *num = [change objectForKey:@"new"];
NSInteger hungry = [num integerValue];
//e) 做判斷
if (hungry < 80) {
[self eat];
}
}
}
4、移除kvo對象
-(void)dealloc{
[smallCV removeObsever:self forkeyPath:@“indexPath” ];
}