最近稍微有了點(diǎn)時(shí)間,充實(shí)一下自己,惡補(bǔ)了一下基礎(chǔ).
關(guān)于UIViewController,我看了一些其他人的博客,在根據(jù)自己的理解,總結(jié)了一下烙样。
UIViewController 生命周期
1.通過alloc init 分配內(nèi)存,初始化controller.
2.loadView
loadView方法默認(rèn)實(shí)現(xiàn)[super loadView]
如果在初始化controller時(shí)指定了xib文件名,就會(huì)根據(jù)傳入的xib文件名加載對(duì)應(yīng)的xib文件,如果沒傳xib文件名,默認(rèn)會(huì)加載跟controller同名的xib文件,如果沒找到相關(guān)聯(lián)的xib文件,就會(huì)創(chuàng)建一個(gè)空白的UIView,然后賦給controller的view
3.viewDidLoad
當(dāng)loadView創(chuàng)建完view之后會(huì)調(diào)用viewDidLoad方法
一般我會(huì)在這里做界面上的初始化操作谒获,比如添加按鈕,子視圖,等等.
4.viewWillAppear
當(dāng)view在load完之后,將要顯示在屏幕之前會(huì)調(diào)用這個(gè)方法
在重寫這些方法時(shí)候最好先調(diào)用一下系統(tǒng)的方法之后在做操作寻定。比如:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// custom code...
}
stackoverflow上的答案
5.viewDidAppear
當(dāng)view已經(jīng)在屏幕上顯示出來之后,會(huì)調(diào)用這個(gè)方法
當(dāng)一個(gè)視圖被移除屏幕并且銷毀的時(shí)候
1.viewWillDisappear
當(dāng)視圖將要從屏幕上移除時(shí)候調(diào)用
2.viewDidDisappear
當(dāng)視圖已經(jīng)從屏幕上移除時(shí)候調(diào)用
3.dealloc
view被銷毀時(shí)候調(diào)用精耐,如果是手動(dòng)管理內(nèi)存的話,需要釋放掉之前在init和viewDidLoad中分配的內(nèi)存(類似alloc,new,copy)
dealloc方法不能由我們主動(dòng)調(diào)用,必須等引用計(jì)數(shù)為0時(shí)候由系統(tǒng)調(diào)用.
關(guān)于viewDidUnload
在網(wǎng)上看了好多文章 總結(jié)下:
iOS設(shè)備的內(nèi)存是有限的,如果應(yīng)用程序占用的內(nèi)存過多的話,系統(tǒng)就會(huì)對(duì)應(yīng)用程序發(fā)出內(nèi)存警告didReceiveMemoryWarning. 并且調(diào)用viewDidUnload方法.如果controller.view不在應(yīng)用程序的視圖層次結(jié)構(gòu)(View Hierarchy)中,也就是本視圖不是當(dāng)前屏幕上正在顯示的視圖時(shí),就會(huì)將view釋放(先釋放所有子視圖再釋放自己,在這里系統(tǒng)只是釋放內(nèi)存,并沒有釋放對(duì)象的所有權(quán),所以通常我們需要在這里講不需要在內(nèi)存中保留的對(duì)象釋放所有權(quán),也就是指針置為nil) 等本視圖再次顯示在屏幕上時(shí),會(huì)再次調(diào)用viewDidLoad方法向胡。
但是:重要的一點(diǎn)=┣邸P』薄!件豌!
viewDidUnload 在6.0之后已經(jīng)廢棄了。
簡(jiǎn)單來說茧彤,對(duì)于iOS6,你不需要做任何以前viewDidUnload的事情曾掂,更不需要把以前viewDidUnload的代碼移動(dòng)到 didReceiveMemoryWarning方法中壁顶。
引用WWDC 2012 中的一段話來給viewDidUnload說再見:
The method viewWillUnload and viewDidUnload. We’re not going to call them anymore. I mean, there’s kind of a cost-benifit equation and analysis that we went through. In the early days, there was a real performance need for us to ensure that on memory warnings we unloaded views. There was all kinds of graphics and backing stores and so forth that would also get unloaded. We now unload those independently of the view, so it isn’t that big of a deal for us for those to be unloaded, and there were so many bugs where there would be pointers into。