ios - 在 iOS 中检测前台/后台代表的合适位置是什么?
问题描述
背景:
我正在使用 iOS 应用程序。我们有大约 100 个ViewControllers
,我们的应用程序中的所有这些都是从一开始就继承BaseViewController
的。目前在重构时,我看到许多视图控制器需要检测willEnterForegroundNotification
[1]和didEnterBackgroundNotification
[2]
委托来执行一些内部任务。几乎20~25 个视图控制器正在为他们的viewDidLoad
. 我正在考虑将此检测任务移至中央BaseViewController
以使代码清晰。
我提出的解决方案:
我的预期设计如下所示,
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
}
func appMovedToBackground() {
print("App moved to Background!")
}
func appMovedToForeground() {
print("App moved to ForeGround!")
}
}
class MyViewController: BaseViewController {
override func appMovedToBackground() {
print(“Do whatever need to do for current view controllers on appMovedToBackground”)
}
override func appMovedToForeground() {
print(“Do whatever need to do for current view controllers on appMovedToForeground”)
}
}
我看到,如果我将此检测转移到BaseViewController
自定义观察者处理的许多任务中,子视图控制器就会减少。Child ViewControllers(即在示例代码中)只需要在需要时MyViewController
使用这两个功能。appMovedToBackground
appMovedToForeground
问题:
但是,我仍然担心一件事。当我将观察者设置部分移动到BaseViewController
时,所有ViewControllers
(我的项目中大约有 100 个)将在默认情况下注册观察者,viewDidLoad
其中许多甚至不会在现实中使用它们。恐怕这种设计可能会严重影响应用程序的性能。在这种情况下,在性能与代码清晰度和可维护性之间进行权衡时,我的预期设计是否可以接受?在我的情况下有更好的设计吗?
参考:
[1] willEnterForegroundNotification - 当应用程序进入后台时发布。
[2] didEnterBackgroundNotification - 在应用程序离开后台状态成为活动应用程序之前不久发布。
解决方案
您可以声明一个协议,让我们调用它BGFGObserver
。让每一个需要观察前台、后台的VC都对这个协议进行确认。在基类中检查是否self
确认BGFGObserver
,如果是,则仅注册为观察者。在BGFGObserver
你将需要有处理背景和前景的方法。
推荐阅读
- visual-studio-2017 - TFS 2017/VS 2017 取消搁置到不同的分支,或者从“Main”创建一个带有已保存、未提交更改的分支
- jq - jq 将输出组合在以空格分隔的单行上
- sql - “错误:查询没有结果数据的目的地”
- python - Pytests:获取错误函数不使用参数错误
- php - 如何注册/聚集父子类?
- spring-boot - SpringBoot 应用程序在部署到 EC2 实例后 2 天给出 RestClientException(未知状态代码 [494] null)
- php - wkhtmltoimage 的参数列表太长错误
- nsq - NSQ 无法收到消息
- javascript - 正则表达式只允许字母,没有特殊字符,开头没有空格
- java - Java项目的规范项目布局?