是否从NSNotification中删除C++观察器

Remove a C++ observer from NSNotification?

本文关键字:C++ 观察 删除 NSNotification 是否      更新时间:2023-10-16

在C++中,为通知添加一个Observer并不困难。但问题是,我如何才能删除一个观察员。

[[NSNotificationCenter defaultCenter] addObserverForName:@"SENTENCE_FOUND" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {

所以通常我们使用

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

移除观察者。

但是由于C++没有self,当我使用this时,我得到了以下错误

Cannot initialize a parameter of type 'id _Nonnull' with an rvalue of type 'DialogSystem *'

那么,我如何删除C++类观察器呢?或者这是不可能的?

-[NSNotificationCenter addObserverForName:object:queue:usingBlock:]:的文档复制

返回值

充当观察者的不透明物体。

讨论

如果给定的通知触发了一个以上的观察者块,则这些块可以相对于彼此同时执行(但在它们的给定队列或当前线程上(。

以下示例显示了如何注册以接收区域设置更改通知。

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
self.localeChangeObserver = [center addObserverForName:NSCurrentLocaleDidChangeNotification object:nil
queue:mainQueue usingBlock:^(NSNotification *note) { 
NSLog(@"The user's locale changed to: %@", [[NSLocale currentLocale] localeIdentifier]);
}];

要注销观察,请将此方法返回的对象传递给removeObserver:。在释放addObserverForName:object:queue:usingBlock:指定的任何对象之前,必须调用removeObserver:或removeObserver:name:object:。

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self.localeChangeObserver];

编辑:从同一页面复制:

另一种常见模式是通过从观察块中删除观察者来创建一次性通知,如以下示例所示。

NSNotificationCenter * __weak center = [NSNotificationCenter defaultCenter];
id __block token = [center addObserverForName:@"OneTimeNotification"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSLog(@"Received the notification!");
[center removeObserver:token];
}];