標籤:
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.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出來的!
iOS UIViewController 和 nib 相關的3個方法