如果一个类注册某种类型的NSNotificationCenter事件,而另一个类发布该类型的事件,那么接收器中的代码将在发布类继续之前(同步)或之后(异步)执行吗?

- (void)poster {
    [[NSNotificationCenter defaultCenter]
        postNotificationWithName:@"myevent"
        object:nil];
    NSLog(@"Hello from poster");
}

- (void)receiver {
    [[NSNotificationCenter defaultCenter]
        addObserver:self
        selector:@selector:(mySelector)
        name:@"myevent"
        object:nil];
}

- (void) mySelector:(NSNotification *) notification {
    NSLog(@"Hello from receiver");
}

在上面的代码示例中,将在“来自调用者的问候”之前或之后打印“来自接收者的问候”吗?

最佳答案

如NSNotificationCenter文档中所述,NSNotificationCenter Class Reference通知是同步发布的。

通知中心将通知同步发送给观察者。
换句话说,在所有观察者都收到并处理了通知之后,postNotification:方法才返回。要异步发送通知,请使用 NSNotificationQueue

在多线程应用程序中,通知始终在发布通知的线程中传递,该线程可能与观察者自己注册的线程不同。

希望对您有帮助。

关于ios - NSNotificationCenter事件是同步接收还是异步接收?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16298671/

10-11 22:46
查看更多