Contents

万万没想到这个系列能写三篇。这里面的坑罄竹难书,值得大批特批。

一个 vc init 出来之后用 nav push 进去,人畜无害。

然而发现 vc 的 viewDidLoad 里拿不到 self.navigationController,这就很日怪了。其他地方都可以。调了半天没有头绪。只能网上查了。

要不还说 stack overflow 好呢,还就真给查到了。

https://stackoverflow.com/questions/10982567/why-is-self-navigationcontroller-null-in-viewdidload

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.

看到第一句话就秒懂了,这就是这个系列三的来源。

原因是我在外面 vc init 完毕之后立马写了

vc.view.xx = xx;

系列一:《UIViewController 的 init 和 viewDidLoad 执行顺序带来的有趣现象》

系列二:《再谈 init 和 viewDidLoad 执行顺序》

Contents