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.
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.
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.
As an aside, I think you need to rethink your design. It sounds like you don't have sufficient separation between the view and the model.
Your data model should know what is and is not old data and should only return current data to the tableViewController. The data model should have complete control over the integrity of the data and it shouldn't be possible to force it to return the wrong data. It definitely should be impossible that the app will crash owing to such forcing.
精彩评论