今天我发现KVO回调函数- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context是同步函数,示例:
首先,我添加观察者:
[self addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];第二,我设置了回调:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"keyPath->%@",keyPath);
sleep(3);
}第三,我更改了age
self.age = @"12312";
NSLog(@"postEnd");然后记录日志
keyPath->age
//after 3 seconds
postEnd为什么在日志postEnd之后3秒
发布于 2018-04-24 12:00:13
键值观察始终发生在发生更改的线程上,并且始终是同步的。这意味着您可以控制线程,但您也知道,当您的代码完成设置值时,所有的观察都已经完成。
有关KVO的更多细节和更多信息,请参阅KVO上的this article。
https://stackoverflow.com/questions/49992710
复制相似问题