Why is self.navigationController null in viewDidLoad?

前端 未结 1 374
借酒劲吻你
借酒劲吻你 2021-02-01 17:53

I know there are a lot of similar questions, but I can\'t find one that specifically addresses this.

Why is self.navigationController null when called in

相关标签:
1条回答
  • 2021-02-01 18:39

    A view controller's view is loaded when you first access the -view method/property on that controller. After the view has been loaded, the viewDidLoad method is called. This is pretty straight forward. You also have to remember that the view can be loaded/unloaded multiple times if memory warnings are received while the view is off-screen.

    So viewDidLoad does not mean your view controller has been inserted into a navigation controller. In the process of pushing a view controller onto a navigation controller, its view will be accessed and loaded, but this will happen before the whole push is complete. So viewDidLoad is clearly getting called before the navigationController property has been updated.

    You also have to consider that some other part of your code could be accessing the view controller's view before you even push the view controller onto the navigation controller.

    So viewDidLoad is the wrong place to do what you are doing. You probably want to use a method like viewDidAppear: so you know that the view controller's view is part of the view hierarchy when it is invoked.

    0 讨论(0)
提交回复
热议问题