2012-02-17 26 views
1

我可以將觀察者兩次(偶然)添加到通知中心,我將收到兩次通知。 是否有可能只獲得一個通知?你知道更優雅的解決方案嗎?NSNotificationCenter可能導致錯誤。你知道更優雅的解決方案嗎?

我告訴你這個例子,因爲這可能會導致錯誤。

- (void)viewDidLoad 
{ 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardDidShow:) 
              name:UIKeyboardDidShowNotification 
              object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardDidShow:) 
              name:UIKeyboardDidShowNotification 
              object:nil]; 
} 

- (void)keyboardDidShow:(NSNotification *)ntf 
{ 
} 
+1

hm ..如果您多次寫入任何其他相同的代碼,也會導致錯誤。 – beryllium 2012-02-17 16:22:54

回答

1

如果你,如果你添加的觀察者在其他地方還不能確定,可以用下面的代碼每次你要添加觀察員

[[NSNotificationCenter defaultCenter] removeObserver:self name:aName object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:aSelector name:aName object:nil]; 

這樣,要卸下舊的(如果它存在)並添加一個新的。

這不是100%的失敗證明,但它是一個開始。在多線程應用程序中,這些應用程序可能會調用異步或其他獨特的情況,這可能會失敗。

1

您還可以將對象設置爲零,然後將對象設置爲仍然有效。

不是所有的東西都可以做成安全的。

相關問題