iOS UIViewController 和 nib 相关的3个方法
iOS UIViewController 的 awakeFromNib 以及 - (id)initWithCoder:(NSCoder *)aDecoder 和 - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
首先看一下awakeFromNib的官方文档:
The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established. 就是说,awakeFromNib函数中,可以保证所有的IBoutlet链接都有效,而- (id)initWithCoder:(NSCoder *)aDecoder函数中,仅仅能保证self的实例化,无法保证在xib中的其他对象也实例化完毕,所以有的IBoutlet链接有可能是nil!
During the instantiation process, each object in the archive is unarchived and then initialized with the method befitting its type. Objects that conform to the NSCoding protocol (including all subclasses of UIView and UIViewController) are initialized using their initWithCoder: method. All objects that do not conform to the NSCoding protocol are initialized using their init method. After all objects have been instantiated and initialized, the nib-loading code reestablishes the outlet and action connections for all of those objects. It then calls the awakeFromNib method of the objects.
对于UIviewController来说,awakeFromNib 和 - (id)initWithCoder:(NSCoder *)aDecoder是一起出现的,先调用- (id)initWithCoder:(NSCoder *)aDecoder 再调用 awakeFromNib。用storyboard 方法创建的UIViewcontroller就会产生这样的效果。
但是对于使用以前的初始化函数 - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil来生成UIViewcontroller是不会调用上面2个函数的!问什么呢?这其实是2套初始化方法,第一套使用storyboard 方法创建的UIViewcontroller,确实是从nib文件中decode出了 viewcontroller;第二套方法,也用到了nib,但是这个nib仅仅包含view的信息,根本没有包含viewcontroller对象,viewcontroller对象不是从nib中decode出来的!