Felipe
Felipe

Reputation: 508

UINavigationController inside singleton

I have a struct that holds an instance of UINavigationController:

struct NavigationController {
    static let shared = UINavigationController()
}

I use NavigationController.shared to push and pop ViewControllers around the app, rather than using the ViewController's .navigationController property.

The issue I'm having is that when I pop I get new instances of my previous ViewController, this is my hierarchy:

(0) UIWindow
|
---- (1) NavigationController (is set as the UIWindow.rootViewController)
     |
     ---- (2) UITabBarController (is set with NavigationController.shared.setViewControllers)
         |
         ---- (3) ViewController (HomeVC) (is the first tab of the UITabController)
             |
             ---- (4) ViewController (ScanVC) (is pushed into the stack by NavigationController.shared.pushViewController)
         ---- (5) ViewController (NotificationsVC)
         ---- (6) ViewController (SettingsVC)
  1. I put a print statement in my HomeVC in the viewDidLoad method
  2. My understanding is that the viewDidLoad should only be called once in the lifecycle of a ViewController
  3. When I go back to the HomeVC from the ScanVC then the print always gets triggered which means I have a new instance of the HomeVC

This is the print statement I created inside the viewDidLoad method:

print("\(#function) View Did Load, instance: \(self)")

Here's the output from going back and forth from the HomeVC to ScanVC:

viewDidLoad() View Did Load, instance: <HomeVC: 0x118db0000>
viewDidLoad() View Did Load, instance: <HomeVC: 0x118db3100>
viewDidLoad() View Did Load, instance: <HomeVC: 0x118db0700>

Any one has any suggestions on how to fix this? Because ideally going back to the HomeVC should not instantiate a new ViewController.

I tested this on a small test project and viewDidLoad would only be triggered once when the ViewController was instantiated.

Upvotes: -1

Views: 19

Answers (0)

Related Questions