2015-06-11 36 views
0

設置通知時,可以設置不同的選擇器對其作出反應。但似乎沒有辦法通過選擇器刪除通知。例如:Objective-C:如何通過選擇器刪除通知?

// e.g. React to background notification by calling method 1 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method1:) name:notification object:nil]; 


// e.g. React to background notification by calling method 2  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method2:) name:notification object:nil]; 

現在,當通知觸發時,兩種方法都會對它做出反應。 如何選擇性刪除通知(例如,刪除通知處理程序method1)?

+0

它看起來不像你可以,但沒有理由註冊兩種方法來首先在同一類上接收相同的通知。 – Droppy

+0

我的理由是有理由的,因爲這兩個操作明顯不同。 – Boon

+0

在這些條件下從'method1'調用'method2'。無論如何,您需要記住這些條件才能正確刪除通知。 – Droppy

回答

1

有辦法做到這一點,但我不認爲你會喜歡它。

改爲使用-addObserverForName:object:queue:usingBlock:

__weak typeof(self) weakSelf = self; 

// e.g. React to background notification by calling method 1 
self.method1Observer = [[NSNotificationCenter defaultCenter] addObserverForName:notification object:nil queue:nil usingBlock:^(NSNotification *note) { 
    [weakSelf method1:note]; 
}]; 

// e.g. React to background notification by calling method 2  
self.method2Observer = [[NSNotificationCenter defaultCenter] addObserverForName:notification object:nil queue:nil usingBlock:^(NSNotification *note) { 
    [weakSelf method2:note]; 
}]; 

再後來就:

// Remove method 1 observer while keeping method 2 observer. 
if (self.method1Observer != nil) { 
    [[NSNotificationCenter defaultCenter] removeObserver:self.method1Observer]; 
    self.method1Observer = nil; 
} 

更新:我將它傳遞給-removeObserver:之前忘了nil檢查self.method1Observer

+0

這看起來很棒。你爲什麼不認爲我會喜歡它? – Boon

+0

由於增加了複雜性。它需要創建兩個新的屬性,這些屬性只能作爲'-removeObserver:'的佔位符。你還必須小心保留週期(因此'weakSelf'變量)。另外,還有一點間接:目標/動作不是直接調用,而是調用一個塊,然後調用目標動作。沒有一個是真正乾淨的設計。 –

0

您必須在該類不需要時刪除該通知。因此,只需使用下面的代碼刪除已添加的通知。

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"Notification" object:nil];