首页 > 解决方案 > 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只出现一次?

标签: iosios13nsnotifications

解决方案


推荐阅读