从所有VC中删除观察者-迅速

时间:2019-08-28 10:51:11

标签: swift

在示例中:在A vc中,我添加了观察者:

NotificationCenter.default.addObserver(self, selector: #selector(onDidReceive(_:)), name: .didReceive, object: nil)

当我在A vc时,可以删除B vc中的观察者吗?

我尝试过此操作(在B vc中):

NotificationCenter.default.removeObserver(self)

但是没用

有可能做什么?还是我必须在我创建的同一VC中删除观察者?

2 个答案:

答案 0 :(得分:0)

您可以从导航控制器的view controllers属性中获取AVC的实例,并删除观察者。

// BVC

if let vc = self.navigationController?.viewControllers.first(where: { $0 is AVC }) {
    NotificationCenter.default.removeObserver(vc)
}

答案 1 :(得分:0)

只需在添加了观察者的viewController中添加一行

deinit {
    NotificationCenter.default.removeObserver(self)
}

这将删除观察者