ios - viewWillAppear 中添加的 NSNotification Observer 在 iOS 13 中执行了两次
问题描述
NSNotification
我在处理iOS 13时遇到了一个奇怪的问题
// Adding the observer in viewWillAppear
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
...
NSLog(@"Adding observer");
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification) name:@"someNotification" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
...
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"someNotification" object:nil];
NSLog(@"Removed observer");
}
- (void)handleNotification {
NSLog(@"Handle notification");
}
我已经仔细检查了通知只发布了一次。应用程序中只有一个someNotification
发布位置和断点并NSLog
确认,此代码仅执行一次。
在 iOS 12 及更低版本中的结果:
Adding observer
Handle notification
在 iOS 13 及更低版本中的结果:
Adding observer
Handle notification
Handle notification
因此,在 iOS 13 中,观察者被调用了两次,而在 iOS 12 和 Blow 中完全相同的代码只被调用了一次。
我的第一个猜测是,由于某种原因在 iOS 13viewWillAppear
中被调用了两次,因此观察者被添加了两次。但是,在这种情况下,NSLog
输出Adding Observer
也应该出现两次,不是吗?
但是:这个问题可以通过viewWillAppear
在添加之前移除观察者来解决。这样可以确保只添加一次观察者:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
...
NSLog(@"Adding observer");
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"someNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification) name:@"someNotification" object:nil];
}
因此,由于这解决了问题,因此观察者显然被添加了两次。viewWillAppear
但为什么?
为什么viewWillAppear
在 iOS 13 中被调用两次?更重要的是:它怎么可能被调用两次,但NSLog
输出Adding Observer
只出现一次?
解决方案
推荐阅读
- linux - 如何从用户空间访问 thread_info
- vue.js - 如何在 vue data mustache 表达式中使用复杂变量作为对象键?
- c# - 如何从带有分隔符的txt文件中读取文件,并将其写回新的txt文件
- odoo-8 - Odoo重复many2many字段
- c# - ajax将一个int列表传递给asp net api控制器,参数为null
- eclipse - 如何制作开始测验的按钮?
- reactjs - 与 componentWilLReceiveProps 等效的挂钩以更新状态
- reactjs - React:当有多个字段要填充时如何设置状态
- reactjs - Typescript 条件渲染,Type 'undefined' is not Assignable to type CompanyStatsProps
- python - 从菜单调用所有文件