Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does NSNotificationCenter notications have higher priority than UITableView cell loading events?

Are events posted by NSNotificationCenter postNotificationName processed before UI updating events?

I need to know because otherwise my current program will crash in some rare cases.

Model code:

- (void)searchFinishedWithResults:(Results *)results {
    self.results = results;
    // If some table cells are loaded NOW, before notication is processed, we might crash!
    [[NSNotificationCenter defaultCenter]
     postNotificationName:SearchResultArrived object:nil];    
}

When processing the notication, I will run UITableView reloadData.

However, consider if before processing the notication, UI has to be updated. In this case -tableView:cellForRowAtIndexPath:indexPath will be called, but results object has changed, it will fetch old data.

like image 542
Simo Salminen Avatar asked Dec 07 '25 10:12

Simo Salminen


2 Answers

The notifications are dispatched exactly when you call postNotification: or postNotificationName:object:, in a synchronous fashion, one observer after the other (in no particular order). In the case you show, they would be sent exactly after you assign the variable "results" and before the method ends.

like image 186
Adrian Kosmaczewski Avatar answered Dec 09 '25 23:12

Adrian Kosmaczewski


Directly from Apple's documentation on 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.

To send notifications asynchronously use NSNotificationQueue.

like image 26
Georg Schölly Avatar answered Dec 09 '25 22:12

Georg Schölly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!