2

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.

4

2 回答 2

5

没有预期的竞争条件。除了丹唐纳森的回答,这里是另一个引用来自 NSNotificationCenter 的文档:

通知中心同步向观察者发送通知。换句话说, postNotification: 方法在所有观察者都收到并处理通知之前不会返回。要异步发送通知,请使用 NSNotificationQueue。

于 2010-03-24T19:26:52.360 回答
3

我不完全确定您的意思,但我认为这会对您有所帮助:

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

特别是这部分:使用 NSNotificationCenter 的 postNotification: 方法及其变体,可以将通知发布到通知中心。但是,该方法的调用是同步的:在发布对象可以恢复其执行线程之前,它必须等到通知中心将通知分派给所有观察者并返回。

于 2010-03-24T19:24:09.760 回答