下边三种方式都可以:
[self addObserver:self forKeyPath:@"self.now" options:(NSKeyValueObservingOptionNew) context:nil];
[self addObserver:self forKeyPath:@"now" options:(NSKeyValueObservingOptionNew) context:nil];
[self addObserver:self forKeyPath:@"_now" options:(NSKeyValueObservingOptionNew) context:nil];
触发监听
self.now = [NSDate date];// 正常自动触发监听
_now = [NSDate date];// 不能触发监听
/// 手动触发KVO
[self willChangeValueForKey:@"_now"];
[self didChangeValueForKey:@"_now"];
重写set方法事,不需要调用willChangeValueForKey
和didChangeValueForKey
两个方法,如果同时加了,会重复调响应observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
方法;
KVO机制,重写了set方法,必须有self.now(setNow)的操作,不然不能触发监听;
//这三种方式都可以触发
[self setValue:now forKey:@"now"];
[self setNow:[NSDate date]];
self.now = [NSDate date];
//这两种不能触发
[self setValue:now forKey:@"_now"];
_now = [NSDate date];
网友评论