简体   繁体   中英

Why is self.navigationController null in viewDidLoad?

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 viewDidLoad , but correct when called from outside viewDidLoad ?

This is my output from NSLog(@"%@",self.navigationController); The first is called in viewDidLoad , the second I add a button to the interface with a method that calls NSLog(@"%@",self.navigationController); :

NavApp[31524:11003] (null)
NavApp[31524:11003] <UINavigationController: 0x6e21190>

I know there must be some simple explanation for this behavior, I'm just curious as to what it is. Thanks!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM