iOS,为什么observeValueForKeyPath:是同步的

时间:2018-04-24 02:48:14

标签: ios objective-c notifications key-value-observing

今天,我发现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秒?

1 个答案:

答案 0 :(得分:0)

键值观察始终发生在发生更改的线程上,并且始终是同步的。这意味着您可以控制线程,但是您也知道在设置值的代码完成之前所有观察都已完成。

有关KVO的更多详情和更多信息,请参阅KVO上的this article