iOS viewDidUnload方法
轉自:http://blog.csdn.net/chun799/article/details/8951694
在iOS6中,viewDidUnload回調方法被Deprecated掉了。查看蘋果的文檔,可以看到如下的說明。
那么,原本在viewDidUnload中的代碼應該怎么處理?在iOS6中,又應該怎么處理內存警告?帶著這些問題,我查找了一些資料,在此分享給大家。
?
分析
?
在iOS4和iOS5系統中,當內存不足,應用收到Memory warning時,系統會自動調用當前沒在界面上的ViewController的viewDidUnload方法。?通常情況下,這些未顯示在界面上的ViewController是UINavigationController Push棧中未在棧頂的ViewController,以及UITabBarViewController中未顯示的子ViewController。這些View Controller都會在Memory Warning事件發生時,被系統自動調用viewDidUnload方法。
?
在iOS6中,由于viewDidUnload事件在iOS6下任何情況都不會被觸發,所以蘋果在文檔中建議,應該將回收內存的相關操作移到另一個回調函數:didReceiveMemoryWarning?中。但是如果你僅僅是把以前寫到viewDidUnload函數中的代碼移動到didReceiveMemoryWarning函數中,那么你就錯了。以下是一個?錯誤的示例代碼?:
- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; if([self isViewLoaded] && ![[self view] window]) { [self setView:nil]; }?
這篇文章解釋了iOS6不推薦你將view置為nil的原因(鏈接打開需要FQ),?翻譯過來如下:
UIView有一個CALayer的成員變量,CALayer是具體用于將自己畫到屏幕上的。如下圖所示:?
CALayer是一個bitmap圖象的容器類,當UIView調用自身的drawRect時,CALayer才會創建這個bitmap圖象類。
?
具體占內存的其實是一個bitmap圖象類,CALayer只占48bytes, UIView只占96bytes。而一個iPad的全屏UIView的bitmap類會占到12M的大小!
?
在iOS6時,當系統發出MemoryWarning時,系統會自動回收bitmap類。但是不回收UIView和CALayer類。這樣即回收了大部分內存,又能在需要bitmap類時,通過調用UIView的drawRect:?方法重建。
?
內存優化
?
另外文章中還提到蘋果的操作系統對此做的一個內存優化技巧,解釋如下:
?
當一段內存被分配時,它會被標記成“In use“,?以防止被重復使用。當內存被釋放時,這段內存會被標記成”Not?inuse”,這樣,在有新的內存申請時,這塊內存就可能被分配給其它變量。
?
CALayer包括的具體的bitmap內容的私有成員變量類型為CABackingStore,?當收到MemroyWarning時,CABackingStore類型的內存區會被標記成volatile類型(這里的volatile和?C以及Java語言的volatile不是一個意思),volatile表示,這塊內存可能被再次被原變量重用。
?
這樣,有了上面的優化后,當收到Memoy Warning時,雖然所有的CALayer所包含的bitmap內存都被標記成volatile了,但是只要這塊內存沒有再次被復用,那么當需要重建bitmap內存時,?它就可以直接被復用,而避免了再次調用?UIView的?drawRect:?方法。
?
總結
?
所以,簡單來說,對于iOS6,你不需要做任何以前viewDidUnload的事情,更不需要把以前viewDidUnload的代碼移動到?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。
總結
以上是生活随笔為你收集整理的iOS viewDidUnload方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle checkpoint详解
- 下一篇: mysql的内存表和临时表