在示例中:在A vc
中,我添加了观察者:
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceive(_:)), name: .didReceive, object: nil)
当我在A vc
时,可以删除B vc
中的观察者吗?
我尝试过此操作(在B vc
中):
NotificationCenter.default.removeObserver(self)
但是没用
有可能做什么?还是我必须在我创建的同一VC中删除观察者?
答案 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)
}
这将删除观察者