My viewDidLoad
in a view controller is called twice. Once by [UIViewController View]
and a second time by [UINib instanciateWithOwner:Options]
. Why is this happening? Can it be prevented?
viewDidLoad() is only called once, when the view is loaded from a . storyboard file. viewWillAppear(_:) is called every time the view appears. In this simple app, that means it is only called once.
viewWillAppear(_:)Always called after viewDidLoad (for obvious reasons, if you think about it), and just before the view appears on the screen to the user, viewWillAppear is called.
viewDidLoad is called once when the controller is created and viewDidAppear is called each time the view, well, DID appear. So say you have a modal view that you present, when that view is dismissed, viewDidAppear will be called, and viewDidLoad will not be called.
viewDidLoad is called when the ViewController has loaded its view hierarchy into memory. This is the point where you can perform your customized initialisation for your view controller. For instance, if your view controller has a UILabel and you want to set a custom text to it, this is the point where you do that.
Thus, viewDidLoad is sent to a view controller right after its XIB file is loaded to allow you to perform this additional customization of views. It exists specifically for this, and only this. (In cases where you create your view programmatically with loadView, there is no reason to use viewDidLoad.)
Any code you put inside of viewDidLoad
should be able to run multiple times with out any issues. If you have code that only needs to run once for your controller use -awakeFromNib
. The reason is because the view of the view controller can be unloaded and loaded multiple times. The code inside of viewDidLoad
should only modify the UI to reflect the current state.
Now that I got that out of the way, your particular issue looks to be a bug. See Ned's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With