OC- navigationController 为nil 的情况

在iOS开发中,遇到一个子控制器在viewDidLoad时获取navigationController为nil的情况。问题源于addChildViewController、addSubview和设置frame的调用顺序。addChildViewController用于创建父子控制器关系,必须在添加子控制器的view之前调用,以使子控制器能访问到父控制器的navigationController。如果在viewDidLoad之后调用,由于加载时机问题,可能导致无法获取到navigationController。调整顺序或在正确位置进行操作可以避免这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在工作中遇到这样一个问题 一个容器有两个childController 在子Controller 中的viewDidLoad中获取self.navigationController 的时候发现为nil 不理解 addChildViewController:  addSubview: 以及设置view的frame方法的调用顺序影响了

addChildViewController: 在iOS5.0之后开始使用 一个controller 对应一个view 降低耦合度

当然一系列的调用顺序大家也要注意..别的博客中也给了大体的顺序.

在developer 中可以看到 

Discussion

This method creates a parent-child relationship between the current view controller and the object in the childController parameter. This relationship is necessary when embedding the child view controller’s view into the current view controller’s content. If the new child view controller is already the child of a container view controller, it is removed from that container before being added.

This method is only intended to be called by an implementation of a custom container view controller. If you override this method, you must call super in your implementation.

This relationship is necessary when embedding the child view controller’s view into the current view controller’s content. 

当你要吧一个viewController的view 放到另一个controller的view上可以理解为 addSubview: 时 是必须要addChildViewController:的,所以我们可以理解为要先调用addChildViewController: 再调用addSubview:

只有调用了addChildViewController:  子控制器才能拿到父控制器的navigationController 以及navigationItme等对象.可以方便控制.而viewDidLoad的调用时机是

This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView method. You usually override this method to perform additional initialization on views that were loaded from nib files.

所以在调用了self.view addSubview 之后就走了viewDidLoad 来不及获取到父视图的navigation相关的东西.所以就是nil 调整顺序之后就没有这个顾虑了...或者有别的原因大家可以跟我说一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值