首页 > 解决方案 > 在 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使用这两个功能。appMovedToBackgroundappMovedToForeground

问题:

但是,我仍然担心一件事。当我将观察者设置部分移动到BaseViewController时,所有ViewControllers(我的项目中大约有 100 个)将在默认情况下注册观察者,viewDidLoad其中许多甚至不会在现实中使用它们。恐怕这种设计可能会严重影响应用程序的性能。在这种情况下,在性能与代码清晰度和可维护性之间进行权衡时,我的预期设计是否可以接受?在我的情况下有更好的设计吗?


参考:

[1] willEnterForegroundNotification - 当应用程序进入后台时发布。

[2] didEnterBackgroundNotification - 在应用程序离开后台状态成为活动应用程序之前不久发布。

标签: iosswiftdesign-patternsuiviewcontrollerappdelegate

解决方案


您可以声明一个协议,让我们调用它BGFGObserver。让每一个需要观察前台、后台的VC都对这个协议进行确认。在基类中检查是否self确认BGFGObserver,如果是,则仅注册为观察者。在BGFGObserver你将需要有处理背景和前景的方法。


推荐阅读