本文的Demo工程代码参考这里的StudyUIViewAndUIVC
目录
加载
加载的完整过程: 初始化 -> loadView -> viewDidLoad -> viewWillAppear -> viewWillLayoutSubviews -> viewDidLayoutSubviews -> viewDidAppear
初始化
- 原型
UIViewController初始化有以下三个方法
- (id)init;
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (instancetype)initWithCoder:(NSCoder *)aDecode;
- 触发
当通过init或new方法创建UIViewController对象时, 会依次调用
init -> initWithNibName:bundle:
当通过storyboard直接由系统创建UIViewController对象时, 会调用
initWithCoder:
关于初始化更准确的原文描述请参考Apple Developer API Reference
loadView
- 原型
- (void)loadView;
- 触发
The view controller calls this method when its view property is requested but is currently nil
- 备注
1: 不要直接调用该方法!!!
2: 如果使用代码维护views, 必须重写该方法; 如果使用Interface Builder维护views, 不能重写该方法
viewDidLoad
- 原型
- (void)viewDidLoad;
- 触发
This method is called after the view controller has loaded its view hierarchy into memory
viewWillAppear
- 原型
- (void)viewWillAppear:(BOOL)animated;
- 触发
This method is called before the view controller'��s view is about to be added to a view hierarchy and before any animations are configured for showing the view
viewWillLayoutSubviews
- 原型
- (void)viewWillLayoutSubviews;
- 触发
This method is called every time the frame changes like for example when rotate or it’s marked as needing layout
viewDidLayoutSubviews
- 原型
- (void)viewDidLayoutSubviews;
- 触发
When the bounds change for a view controller'��s view, the view adjusts the positions of its subviews and then the system calls this method
viewDidAppear
- 原型
- (void)viewDidAppear:(BOOL)animated;
- 触发
This method is executed after the animation displaying the view finishes so in this step the view is already visible for the user
- 备注
1: 在该方法适合做这些操作: 获取数据(从数据存储或网络)并显示到view
卸载
卸载的完整过程: viewWillDisappear -> viewDidDisappear -> dealloc
viewWillDisappear
- 原型
- (void)viewWillDisappear:(BOOL)animated;
- 触发
This method is called before the view is actually removed and before any animations are configured
viewDidDisappear
- 原型
- (void)viewDidDisappear:(BOOL)animated;
- 触发
You can override this method to perform additional tasks associated with dismissing or hiding the view
dealloc
- 原型
- (void)dealloc;
- 触发
在没有内存泄漏的情况下, dealloc是肯定会被调用的, 即使延迟释放(例如autoreleasepool)情况下, 肯定也是会被调用的
所以很多内存泄漏检测工具就是基于此, 例如MLeaksFinder
- 备注
1: You override this method to dispose of resources other than the object’s instance variables
答疑
构建view hierarchy要放在加载时的哪个方法中?
尽可能地使用Interface Builder维护views
如果必须使用代码, 理论上需要放在loadView中, 但是因为
加载时的viewDidLoad方法中适合做什么操作?
viewDidLoad适合做与UI无关的数据和模型的操作
切记不要在viewDidLoad做view hierarchy和布局的操作
sub views布局要放在加载时的哪个方法中?
非autolayout的布局必须要放到viewWillLayoutSubviews
viewDidLoad中只确定了view的bounds, 而没有确定orientation; viewWillLayoutSubviews中才真正确定了view的布局
哪些方法需要调用父类的方法?
这些方法必须调用父类的方法([super xyz]): viewWillAppear / viewDidAppear; viewDidDisappear / viewDidDisappear
如果父类是UIViewController, viewDidLoad方法可以不必调用父类的方法; 如果父类是自定义类, 根据实际情况决定是否要调用
关于是否需要调用父类方法更准确的原文描述请参考Apple Developer API Reference的各接口说明
参考
更多文章, 请支持我的个人博客