NSNotificationCenter事件是同步还是异步接收的? [英] Are NSNotificationCenter events received synchronously or asynchronously?

查看:334
本文介绍了NSNotificationCenter事件是同步还是异步接收的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

- (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");
}

在上面的代码示例中,来自接收器的Hello将在之前打印或者在来自调用者的Hello之后?

In the code example above, will "Hello from receiver" be printed before or after "Hello from caller"?

推荐答案

如NSNotificationCenter的文档中所述NSNotificationCenter类参考通知同步。

As stated in the documentation for NSNotificationCenter NSNotificationCenter Class Reference notifications are posted synchronously.

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

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. To send notifications asynchronously use 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.

希望它可以帮到你。

这篇关于NSNotificationCenter事件是同步还是异步接收的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆