发布两个 NSNotification 时的执行顺序

发布于 2024-10-20 01:02:20 字数 929 浏览 3 评论 0原文

关于 NSNotification 的一个简单问题...如果我在一个方法中发布两个 NSNotification,并且它们被不同的对象观察,那么选择器方法的执行顺序是什么?

例如,如果我有三个控制器 - Poster、Receiver A 和 Receiver B。在 Poster 控制器的函数中,我执行以下操作:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ReceiverADoSomething" object:self];
[[NSNotificationCenter defaultCenter] postNotificationName:@"ReceiverBDoSomething" object:self];

在接收器 A 的 viewDidLoad 方法中:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(workToDoByA:) name:@"ReceiverADoSomething" object:nil];

在接收器 B 的 viewDidLoad 方法中:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(workToDoByB:) name:@"ReceiverADoSomething" object:nil];

Will 先完成workToDoByA,然后再完成workToDoByB? 还是一起被处决?

另一种情况...如果我让海报 A 发布通知,但同一个通知有两个观察者。那么执行顺序是怎样的呢?

预先感谢您的帮助。

A quick question about NSNotification... If I post two NSNotifications in a method, and they are observed by different objects, what is the sequence of execution of the selector method?

For instance, if I have three controllers - Poster, Receiver A and Receiver B. In a function of the Poster controller, I do the following:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ReceiverADoSomething" object:self];
[[NSNotificationCenter defaultCenter] postNotificationName:@"ReceiverBDoSomething" object:self];

In the viewDidLoad method for receiver A:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(workToDoByA:) name:@"ReceiverADoSomething" object:nil];

In the viewDidLoad method for receiver B:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(workToDoByB:) name:@"ReceiverADoSomething" object:nil];

Will workToDoByA be done first followed by workToDoByB?
Or they will be executed together?

Another scenario... If I have Poster A posting a notification but there are two observers to the SAME notification. What is the execution sequence then?

Thanks in advance for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡の花香 2024-10-27 01:02:20

摘自 Apple 文档

通知中心同步向观察者发送通知。换句话说,postNotification: 方法直到所有观察者都收到并处理了通知后才会返回。要异步发送通知,请使用 NSNotificationQueue。在多线程应用程序中,通知始终在发布通知的线程中传递,该线程可能与观察者注册自身的线程不同。

postNotificationName 的策略相同。

A excerpt from Apple docs:

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.

the same policy is for postNotificationName.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文