initwithcoder什么時(shí)候調(diào)用
第一抚笔、initWithNibName這個(gè)方法是在controller的類在IB中創(chuàng)建,但是通過Xcode實(shí)例化controller的時(shí)候用的.
第二、initWithCoder 是一個(gè)類在IB中創(chuàng)建但在xocde中被實(shí)例化時(shí)被調(diào)用的.比如,通過IB創(chuàng)建一個(gè)controller的nib文件,然后在xcode中通過 initWithNibName來實(shí)例化這個(gè)controller,那么這個(gè)controller的initWithCoder會被調(diào)用.或者是一個(gè)view的nib文件侨拦,類似方法創(chuàng)建時(shí)調(diào)用initWithCoder
第三殊橙、awakeFromNib
當(dāng).nib文件被加載的時(shí)候,會發(fā)送一個(gè)awakeFromNib的消息到.nib文件中的每個(gè)對象狱从,每個(gè)對象都可以定義自己的awakeFromNib函數(shù)來響應(yīng)這個(gè)消息膨蛮,執(zhí)行一些必要的操作。也就是說通過nib文件創(chuàng)建view對象時(shí)執(zhí)行awakeFromNib
第四矫夯、關(guān)于 initWithNibName 和 loadNibNamed 的區(qū)別和聯(lián)系 :
關(guān)于 initWithNibName 和 loadNibNamed 的區(qū)別和聯(lián)系鸽疾。之所以要把這兩者來一起講,我覺的我也有點(diǎn)困惑训貌,到底用那種制肮?其實(shí)真正搞清楚了他們之間的差別,就不會這么迷惘了递沪。因?yàn)檫@兩個(gè)方法豺鼻,根本就不是一路貨色。
既然款慨,是要說明這2個(gè)方法儒飒,那就著重將區(qū)別吧。
但是第一步檩奠,還是要羅嗦一下桩了,他們的聯(lián)系:可以使用此方法加載用戶界面(xib文件)到我們的代碼中,這樣埠戳,可以通過操作這個(gè)加載進(jìn)來的(xib)對象井誉,來操作xib文件內(nèi)容。
下面進(jìn)入主題整胃,談區(qū)別:
- ShowViewController的initWithNibName方法
ShowViewController * showMessage = [[ShowViewController alloc]
initWithNibName:@"ShowViewController" bundle:nil];
self.showViewController = showMessage;
[showMessage release];
2.VideoCellController的loadNibNamed方法
NSArray * nib = [[NSBundle mainBundle] loadNibNamed:@"Save3ViewController"
owner:self options:nil] ;
總結(jié):
只看他們初始化颗圣,那可能感覺是一樣的。但是如果奔则,打開分別看xib的關(guān)系的時(shí)候蔽午,才恍然大悟,原來他們的集成類都不一樣疾呻。 - initWithNibName要加載的xib的類為我們定義的視圖控制器類
2.加載方式不同
initWithNibName方法:是延遲加載写半,這個(gè)View上的控件是 nil 的,只有到 需要顯示時(shí)璃岳,才會不是 nil
loadNibNamed方法:即時(shí)加載铃慷,用該方法加載的xib對象中的各個(gè)元素都已經(jīng)存在蜕该。
(認(rèn)真理解這句幫規(guī):when using loadNibNamed:owner:options:, the File's Owner should be NSObject, the main view should be your class type, and all outlets should be hooked up to the view, not the File's Owner.)
第五、initWithCoder和initWithFrame的區(qū)別
nitWithoder 是當(dāng)從nib文件中加載對象的時(shí)候會調(diào)用馋缅,比如你的view來自nib那么就會調(diào)用這個(gè)view的這個(gè)函數(shù)绢淀。(由框架調(diào)用)
initWithFrame (是由用戶調(diào)用,來初始化對象的)
The init method that gets used depends on how the view is created. It can be explicitly created using initWithFrame or it can be created by loading a nib. In that case, the initWithCoder method gets called when the view is loaded from the nib. There are other init methods for subclasses (like UITableViewController has initWithStyle), so you have to be sure which one is being called.
self.showViewController = [nib lastObject];
[nib objectAtIndex:0];