前言
在工作中遇到这样一个问题 一个容器有两个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 调整顺序之后就没有这个顾虑了...或者有别的原因大家可以跟我说一下