我正在使用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
,则从子视图控制器减少了许多自定义观察者处理任务。子ViewController(即示例代码中的MyViewController
)仅在需要时才需要使用这两个函数appMovedToBackground
和appMovedToForeground
。
但是,我仍然担心一件事。当我将观察者设置部分移至BaseViewController
时,因此所有ViewControllers
(在我的项目中大约有100个)将在其默认的viewDidLoad
中注册观察者,并且其中许多甚至不会在实际中使用它们。恐怕这种设计可能会严重影响应用性能。在这种情况下在性能与代码清晰度和可维护性之间进行权衡时,我的预期设计是否可以接受?我的情况下有更好的设计吗?
[1] willEnterForegroundNotification-当应用程序进入后台时发布。
[2] didEnterBackgroundNotification-在应用离开成为活动应用的方式离开背景状态之前不久发布。
您可以声明一个协议,将其称为BGFGObserver
。让需要观察其前景,背景的每个VC对此协议进行确认。在基类中检查self
是否确认为BGFGObserver
,如果是,则仅注册为观察者。在BGFGObserver
中,您将需要具有处理背景和前景的方法。