2015-06-11 38 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];