[trans] 正确处理 Memory Warning

Will the component create by xib be release in viewDidUnload, I think some component create by code in ViewDidLoad will not be release in ViewDidUnload, but it may be recreate when the ViewDidLoad is called by didReceiveMemoryWarning, that may cause it worse

IPhone下每个app可用的内存是被限制的,如果一个app使用的内存超过20M,则系统会向该app发送Memory Warning消息。收到此消息后,app必须正确处理,否则可能出错或者出现内存泄露。

app收到Memory Warning后会调用:

UIApplication::didReceiveMemoryWarning -> UIApplicationDelegate::applicationDidReceiveMemoryWarning,然后调用当前所有的viewController进行处理。因此处理的主要工作是在viewController。

我们知道,创建viewcontroller时,执行顺序是loadview -> viewDidLoad。

当收到内存警告时,如果viewcontroller未显示(在后台),会执行didReceiveMemoryWarning -> viewDidUnLoad;如果viewcontroller当前正在显示(在前台),则只执行didReceiveMemoryWarning。

当重新显示该viewController时,执行过viewDidUnLoad的viewcontroller(即原来在后台)会重新调用loadview -> viewDidLoad。

因此主要注意下面几个函数:

loadView 创建view,构建界面;
viewDidLoad 做些初始化工作。由于在初次创建viewcontroller和重新恢复时都会调用,因此这个函数需要注意区分不同的情况,设置正确的状态。
didReceiveMemoryWarning 释放不必须的内存,比如缓存,未显示的view等。
viewDidUnLoad 最大程度的释放可以释放的内存。比如应该释放view,这些view在调用loadview后可以重新生成。(其中成员变量释放后应设置为nil)。对于非界面的数据是否释放,需要具体分析,可以恢复的数据可以释放,不能恢复的数据就不要释放。

实际中如果viewcontroller是用xib生成的界面,则需要我们做的就比较少,主要是在viewDidLoad中恢复原来的界面状态。

如果是通过编程创建的界面,则需要做的工作就要更多些,上面4个函数中都需要进行正确处理。

猜你喜欢

转载自shappy1978.iteye.com/blog/1848733
今日推荐