observeValueForKeyPath总是从主线程调用吗?

时间:2021-12-22 19:44:18

Is observeValueForKeyPath always called from the main thread?

observeValueForKeyPath总是从主线程调用吗?

I'm logging calls with

我正在记录电话

-(void) observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    NSLog(@"KVO: isMainThread %d", [NSThread isMainThread]);
    // ...
}

and it seems to be printing 1 every time, but I was unable to find any guarantee of this in the docs. Can anyone confirm this is the case?

它似乎每次打印1,但我无法在文档中找到任何保证。任何人都可以证实这是事实吗?

1 个解决方案

#1


21  

In general, no.

一般来说,没有。

You receive observeValueForKeyPath:ofObject:change:context: on the thread which changed the value. The setter method that changes the value sends the message to all observers after updating the value and before returning.

您在更改值的线程上收到observeValueForKeyPath:ofObject:change:context:。更改值的setter方法在更新值之后和返回之前将消息发送给所有观察者。

If you only call the setter on the main thread, then you will only observe the change on the main thread.

如果您只在主线程上调用setter,那么您将只观察主线程上的更改。

#1


21  

In general, no.

一般来说,没有。

You receive observeValueForKeyPath:ofObject:change:context: on the thread which changed the value. The setter method that changes the value sends the message to all observers after updating the value and before returning.

您在更改值的线程上收到observeValueForKeyPath:ofObject:change:context:。更改值的setter方法在更新值之后和返回之前将消息发送给所有观察者。

If you only call the setter on the main thread, then you will only observe the change on the main thread.

如果您只在主线程上调用setter,那么您将只观察主线程上的更改。