2010-03-24 54 views
2

在單個線程中使用NSNotifications時是否存在競態條件問題?下面是一個示例方法:NSNotification競爭條件

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

}

的條件後的前兩個電話將觸發將由mainPane接收NSNotifications。 mainPane是否保證在收到通知後收到playerToggled消息?我應該說這個代碼似乎按照需要工作(playerToggled總是最後執行)。但我不確定在通知周圍存在什麼時間問題,我找不到具體的答案。

+0

順便說一句,你應該真的接受你到目前爲止詢問的10個問題的一些答案。 –

回答

3

我不完全相信你的意思,但我認爲這將有助於你:

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

特別是這部分: 使用NSNotificationCenter的postNotification:法及其變種,您可以發佈向通知中心發送通知。但是,該方法的調用是同步的:在發佈對象可以恢復其執行線程之前,它必須等到通知中心將通知分派給所有觀察者並返回。

5

有沒有競爭條件的預期。除了Dan Donaldson的回答外,這裏還有NSNotificationCenter的文檔中的另一個引用:

通知中心同步向觀察者發送通知。換句話說,直到所有觀察者都收到並處理了通知之後,postNotification:方法纔會返回。要異步發送通知,請使用NSNotificationQueue。