iOS在开发过程当中内存出现不足,应当怎样解决,内存警告

本文主要讲述了当iOS应用出现内存不足时,如何解决该问题,如今把相关的思路和实现代码整理出来分享给iOS程序员,但愿给他们的开发工做带来帮助。
内存警告
ios下每一个app可用的内存是被限制的,若是一个app使用的内存超过了这个阀值,则系统会向该app发送Memory Warning消息。收到消息后,app必须尽量多的释放一些没必要要的内存,不然OS会关闭app。
几种内存警告级别(便于理解内存警告以后的行为)
Memory warning level:ios

复制代码 代码以下:
typedef enum {
OSMemoryNotificationLevelAny      = -1,
OSMemoryNotificationLevelNormal   =  0,
OSMemoryNotificationLevelWarning  =  1,
OSMemoryNotificationLevelUrgent   =  2,
OSMemoryNotificationLevelCritical =  3
}OSMemoryNotificationLevel;(5.0之后废弃了)

一、Warning (not-normal) ― 退出或者关闭一些没必要要的后台程序 e.g. Mail
二、Urgent ― 退出全部的后台程序 e.g. Safari and iPod.
三、Critical and beyond ― 重启程序员

响应内存警告:
在应用程序委托中实现applicationDidReceiveMemoryWarning:方法:
应用程序委托对象中接收内存警告消息
在您的UIViewController子类中实现didReceiveMemoryWarning方法:
视图控制器中接收内存警告消息
注册UIApplicationDidReceiveMemoryWarningNotification通知:
其它类中使用通知接收内存警告消息(例如:清理缓存数据)数据库

View Controller缓存

生成view:
loadView
一、loadView在每一次使用self.view这个property,而且self.view为nil的时候被调用,用以产生一个有效的self.view(手工维护views,必须重写该方法)
二、view 控制器收到didReceiveMemoryWarning的消息时, 默认的实现是检查当前控制器的view是否在使用。 若是它的view不在当前正在使用的view hierarchy里面,且你的控制器实现了loadView方法,那么这个view将被release, loadView方法将被再次调用来建立一个新的view。(注:ios6.0如下 若是没有实现loadview,内存警告时不会调用viewDidUnload)
viewDidLoad
通常咱们会在这里作界面上的初始化操做,好比往view中添加一些子视图、从数据库或者网络加载模型数据到子视图中
官网提供的生成view的流程图:
2015107101638194
官网提供的卸载view的流程图:
2015107101704363
On iOS 5 and Earlier
1 系统发出警告或者ViewController自己调用致使didReceiveMemoryWarning被调用
2 调用viewWillUnload以后释放View
3 调用viewDidUnload
ios5.0 LeaksDemo网络

复制代码 代码以下:
 -(void)didReceiveMemoryWarning
{
//In earlier versions of iOS, the system automatically attempts to unload a view controller's views when memory is low
[super didReceiveMemoryWarning];

//didReceiveMemoryWarining 会判断当前ViewController的view是否显示在window上,若是没有显示在window上,则didReceiveMemoryWarining 会自动将viewcontroller 的view以及其全部子view所有销毁,而后调用viewcontroller的viewdidunload方法。app

}
- (void)viewDidUnload
{
// 被release的对象必须是在 viewDidLoad中能从新建立的对象
// For example:
self.myOutlet = nil;
self.tableView = nil;
dataArray = nil;spa

[super viewDidUnload];
}code