简体   繁体   English

NSNotificationCenter事件是同步接收还是异步接收?

[英]Are NSNotificationCenter events received synchronously or asynchronously?

If a class registers for NSNotificationCenter events of a certain type and another class posts an event of that type, will the code in the receiver execute before (synchronously) or after (asynchronously) the posting class continues? 如果某个类注册了某种类型的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");
}

In the code example above, will "Hello from receiver" be printed before or after "Hello from caller"? 在上面的代码示例中,将在“来自呼叫者的问候”之前或之后打印“来自接收者的问候”吗?

As stated in the documentation for NSNotificationCenter NSNotificationCenter Class Reference notifications are posted synchronously. 如NSNotificationCenter文档中所述,NSNotificationCenter 类参考通知是同步发布的。

A notification center delivers notifications to observers synchronously. 通知中心将通知同步发送给观察者。 In other words, the postNotification: methods do not return until all observers have received and processed the notification. 换句话说,在所有观察者都收到并处理了通知之后,postNotification:方法才返回。 To send notifications asynchronously use NSNotificationQueue . 要异步发送通知,请使用NSNotificationQueue

In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself. 在多线程应用程序中,通知始终在发布通知的线程中传递,该线程可能与观察者自己注册的线程不同。

Hope it helps you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM