Variable not changed in custom initialiser

2019-07-26 04:06发布

问题:

I am trying to set a value of variable in swift when initialising an instance of a UINavigationController subclass. The code looks like this:

private var initWithRootViewController = false

init() {
    super.init(rootViewController: contentVC)
    initWithRootViewController = true
}

init(parameters: OAuth2Parameters) {
    initWithRootViewController = true
    super.init(rootViewController: contentVC)
    initWithRootViewController = true
    //defer { initWithRootViewController = true }
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

    //initWithRootViewController = true
}

override func viewDidLoad() {
    super.viewDidLoad()

    if !initWithRootViewController {
        setViewControllers([contentVC], animated: false)
    }
}

The problem is that in my custom initialiser (init(parameters: OAuth2Parameters)) the value of initWithRootViewController is never changed. I have even tried to set it before and after super.init is called as shown in the code and to set it after initialisation (commented defer line). Neither works. I have also tried to clean (and clean build folder) in Xcode and reset the simulator.

I inspected the value of initWithRootViewController by setting breakpoints. What I discovered was that in the custom initialiser the property changes value to true, but as soon as it goes out of the scope of the initialiser (when init(nibName...) is called), the value says false and it stays like that when inspected in If I change the value in init(nibName...) then it is set properly. Why can I not change the value of the variable in my custom init method?