mardi 17 décembre 2019

What are proper places to detect foreground/background delegates in iOS?

Backgound:

I am working in an iOS application. We have around 100 ViewControllers and all of them in our application are inherited from BaseViewController from the beginning. Currently while refactoring, I see many view controllers require to detect willEnterForegroundNotification[1] and didEnterBackgroundNotification[2] delegates to do some internal tasks. Almost 20~25 view controllers are setting their own notification observers to the delegates on their viewDidLoad. I was thinking to move this detection task to central BaseViewController for code clarity.

My Proposed Solution:

My intended design is like below,

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”)
    }
}

I see that if I move this detection into BaseViewController many tasks of custom observer handling are reduced from child view controllers. Child ViewControllers (i.e. MyViewController in example code) only need to use these two functions appMovedToBackground and appMovedToForeground when they require.

Issues:

However, I am still concern about one thing. As I am moving the observer setting part into BaseViewController, thus all the ViewControllers (approx 100 of them in my project) will register the observer in their default viewDidLoad and many of them won’t even use them in reality. I am afraid this design might heavily costs app performance. Is my intended design acceptable when trading of between performance vs code clarity and maintainability in such situation? Is there any better design in my case?


Reference:

[1] willEnterForegroundNotification - Posted when the app enters the background.

[2] didEnterBackgroundNotification - Posted shortly before an app leaves the background state on its way to becoming the active app.

Aucun commentaire:

Enregistrer un commentaire