Search code examples
iphonecocoarace-conditionnsnotifications

NSNotification race condition


Are there any race condition issues when using NSNotifications within a single thread? Here is a sample method:

- (void) playerToggled: (NSNotification *) notification {
if (timerPane.playing && ! timerPane.paused) {
    [playerPane toggleCurrentPlayer];
    [timerPane toggleTimer];
    [mainPane playerToggled];
}

}

The first two calls after the condition will trigger NSNotifications that will be received by mainPane. Is mainPane guaranteed to receive the playerToggled message after those notifications? I should say that this code seems to work as desired (playerToggled always executes last). But I'm not sure what timing issues there are around notifications and I can't find a specific answer.


Solution

  • I am not exactly sure what you mean, but I think this will be helpful to you:

    http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/Notifications/Articles/NotificationQueues.html#//apple_ref/doc/uid/20000217

    Especially this part: Using the NSNotificationCenter’s postNotification: method and its variants, you can post a notification to a notification center. However, the invocation of the method is synchronous: before the posting object can resume its thread of execution, it must wait until the notification center dispatches the notification to all observers and returns.