Objective-C: 如何删除选择器的通知?

Objective-C: How to remove notification by selector?

设置通知时,您可以设置不同的选择器来响应它。但是似乎没有办法通过选择器删除通知。例如:

// 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)?

有一种方法可以做到,但我认为你不会喜欢它。

改用-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;
}

更新: 我忘了 nil 在传递给 -removeObserver: 之前检查 self.method1Observer

您必须在 class 中不需要时删除该通知。因此,只需使用下面的代码即可删除已添加的通知。

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