gpt4 book ai didi

ios - Swift - 调用 .removeObserver 的正确位置总是 deinit() 吗?

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:54 25 4
gpt4 key购买 nike

这里是 StackOverflow 的新用户(第一次发帖,没有帐户潜伏了很长时间)。在我开始之前,这些是我发现有帮助但没有完全解决我的问题的一些以前回答的问题:

How to safely removeObserver (Swift)

The right place to call .removeObserver for NSNotificationCenter = Swift deinit()?

从这些我构建了一个 BaseView Controller ,用它来控制我的应用程序在各种情况下的行为(例如,当应用程序被带回前台时检查更新的 API 调用)

class BaseViewController : UIViewController {

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}

@objc func applicationWillEnterForeground() {

}

@objc func applicationDidEnterBackground() {

}

deinit {
print("WORKING - deinit BaseViewController")
NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}

}

但是,我的问题是我需要使用其他 NotificationCenter 观察器来动态控制导航(进度)栏,这取决于用户在应用程序中的位置(以及他们在那里做什么,与其他区域隔离) .

我的问题是:“调用 .removeObserver 的正确位置总是 deinit() 吗?” 或者,如果不是,是否有任何关键位置应该考虑添加 .removeObserver 调用?

如果有帮助,应用程序每个部分的导航栏都附加到 MainPagerVC(UIPageViewController),它通过 LGSideMenuController 重用和切换

最佳答案

在您的情况下,您应该在 viewWillDisappear 中移除观察者

override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}

关于ios - Swift - 调用 .removeObserver 的正确位置总是 deinit() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53394779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com