2015-06-18 146 views
2

我有三個viewControllers,我試圖發送一個通知從viewController 3到viewController 1和2.我認爲最好的方法是使用NSNotification。這是我到目前爲止有:我應該從哪裏把removeObserver從NSNotification

在C類 - 發佈通知

[[NSNotificationCenter defaultCenter] postNotficationName:@"Updated "object:self]; 

在B類

在類和B類 - 先註冊爲通知

// viewDidLoad 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdate:) name:@"Updated" object:nil]; 

-(void)handleUpdate:(NSNotification *)notification { 
    NSLog(@"recieved"); 
} 

此功能到目前爲止。但在類A和B,當我去註冊吧:

- (void)viewWillDisappear:(BOOL)animated { 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

handleUpdate方法不會被調用。所以明顯的問題是當我012bd爲notification

我的問題是,如果我迄今所做的一切都是正確的,那麼爲什麼當我刪除removeObserver時它不工作?如果不正確,我可以在哪裏removeObserver's

+3

in方法dealloc –

+0

謝謝!簡直不敢相信! – Jessica

回答

1

你所做的一切都是正確的。這是通知如何工作。 如果您的類A,B總是需要處理更新,您將不會刪除Observer。 因爲您在viewDidLoad中添加了「addObserver」。它意味着你只添加一次Observer。 正常的錯誤是你在「viewWillAppear」或「viewDidAppear」中添加了「addObserver」,它會在類中添加多個觀察者。然後,您必須在viewDidDisappear中移除Observer。

+0

不,不是一切都是對的,是的,你必須在某個時候刪除觀察者 - 在這個類被釋放之前。 – rmaddy

+0

@rmaddy所以我應該在dealloc方法中插入removeObserver? – Jessica

+0

@Jessica是的,就像Reming Hsu建議的一樣。 – rmaddy

相關問題