Execution sequence when two NSNotifications are posted
Asked Answered
P

1

5

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.

Purveyance answered 2/3, 2011 at 7:17 Comment(2)
I'm not an expert, but I would assume that A will execute before B, but you could always NSLog within the controllers and see that order. On another note, I am curious for the answer to your other question about more than one observer to one notification. I have that scenario right now, and only one is firing, so I'd like to know as well...Evert
Never mind, I figured it out. You can have as many observers as you want to a single notification.Evert
P
8

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.

Pentylenetetrazol answered 27/9, 2011 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.