是否从NSNotification中删除C++观察器
Remove a C++ observer from NSNotification?
在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];
}];
相关文章:
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 如何在可观察量列表中使用 RxCpp 运算符?
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 在C++中创建观察器设计模式的好方法
- 是否从NSNotification中删除C++观察器
- 在 ECS 模型中,最合适的观察器容器是什么?
- 反射 + 函数指针与观察者模式
- 观察者模式不起作用
- RXCPP:创建一个不关心可观察量输入类型的扩展
- 观察者带有共同指针
- 如何使用 Eclipse 在 Git 中观察 CLion 项目
- 观察者模式:为什么主题应该是抽象的?
- 如何编写指令重新排序的可观察示例?
- 使用 RxCpp 构建观察者/可观察模式
- 是否可以使用松弛的内存顺序来观察条件?
- C 设计:多个TCP客户端,Boost ASIO和观察者
- 使用POCO的多深度目录观察者
- 观察者模式专业化
- 如何在观察器中处理具有不同状态值类型的可观察量
- C 样本观察者模板类误差