为什么self.navigationController在viewDidLoad中为null? [英] Why is self.navigationController null in viewDidLoad?

查看:150
本文介绍了为什么self.navigationController在viewDidLoad中为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多类似的问题,但是我找不到专门解决这个问题的问题.

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

为什么在viewDidLoad中调用self.navigationController为null,但从viewDidLoad外部调用时是正确的?

Why is self.navigationController null when called in viewDidLoad, but correct when called from outside viewDidLoad?

这是我在NSLog(@"%@",self.navigationController);中的输出,第一个在viewDidLoad中调用,第二个在接口上添加一个调用NSLog(@"%@",self.navigationController);的方法的按钮:

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!

推荐答案

当您首次访问该控制器上的-view方法/属性时,将加载该视图控制器的视图.加载视图后,将调用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.

因此viewDidLoad并不意味着您的视图控制器已插入导航控制器中.在将视图控制器推送到导航控制器的过程中,将访问并加载其view,但这会在整个推送完成之前 发生.因此,navigationController属性显然已在更新navigationController属性之前被调用.

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.

所以viewDidLoad是做您正在做的事情的错误位置.您可能想要使用类似viewDidAppear:的方法,因此您知道在调用视图控制器时,视图控制器是视图层次结构的一部分.

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.

这篇关于为什么self.navigationController在viewDidLoad中为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆