2010-12-23 74 views
7

我在initWithFrame:下創建的自定義UIView中添加了觀察者。如何刪除UIView中的NSNotification的觀察者?

[[NSNotificationCenter defaultCenter] addObserver:self 
     selector:@selector(updateZipFromLocation:) 
      name:@"zipFoundFromLocation" 
      object:nil]; 

問題是,這個視圖是子視圖。當再次加載視圖時,它會再次調用initWithFrame消息,從而添加兩個觀察者等等。如何在視圖消失時刪除觀察者?由於它是UIView,它說viewWillDisappear:(BOOL)animated不是一個有效的方法。有任何想法嗎?

+0

剛擡頭,國際志願者組織是指鍵 - 值觀察,這是不同的概念從'NSNotificationCenter`。 – 2010-12-23 02:48:26

+0

糟糕,所有這些還是有點新的。 :) – 2010-12-23 02:49:45

回答

12

你說過initWithFrame:被多次調用,所以我認爲這意味着視圖被破壞和重新創建。您可以刪除的視圖,dealloc觀察員,當視圖不再被任何人保留其被稱爲:

- (void)dealloc { 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    [super dealloc]; 
}