解析iOS内存不足时的警告以及处理过程

内存警告

ios下每个app可用的内存是被限制的,如果一个app使用的内存超过了这个阀值,则系统会向该app发送Memory Warning消息。收到消息后,app必须尽可能多的释放一些不必要的内存,否则OS会关闭app。

几种内存警告级别(便于理解内存警告之后的行为)

 Memory warning level:

typedef enum {

                     OSMemoryNotificationLevelAny      = -1,

                     OSMemoryNotificationLevelNormal   =  0,

                     OSMemoryNotificationLevelWarning  =  1,

                     OSMemoryNotificationLevelUrgent   =  2,

                     OSMemoryNotificationLevelCritical =  3

                     }OSMemoryNotificationLevel;(5.0以后废弃了)


            1、Warning (not-normal) — 退出或者关闭一些不必要的后台程序 e.g. Mail

            2、Urgent — 退出所有的后台程序 e.g. Safari and iPod.

            3、Critical and beyond — 重启

响应内存警告:

在应用程序委托中实现applicationDidReceiveMemoryWarning:方法:

            应用程序委托对象中接收内存警告消息

在您的UIViewController子类中实现didReceiveMemoryWarning方法:

            视图控制器中接收内存警告消息

注册UIApplicationDidReceiveMemoryWarningNotification通知:

            其它类中使用通知接收内存警告消息(例如:清理缓存数据)

View Controller

生成view:

loadView

1、loadView在每一次使用self.view这个property,并且self.view为nil的时候被调用,用以产生一个有效的self.view(手工维护views,必须重写该方法)

2、view 控制器收到didReceiveMemoryWarning的消息时, 默认的实现是检查当前控制器的view是否在使用。 如果它的view不在当前正在使用的view hierarchy里面,且你的控制器实现了loadView方法,那么这个view将被release, loadView方法将被再次调用来创建一个新的view。(注:ios6.0以下 如果没有实现loadview,内存警告时不会调用viewDidUnload)

viewDidLoad

一般我们会在这里做界面上的初始化操作,比如往view中添加一些子视图、从数据库或者网络加载模型数据到子视图中

官网提供的生成view的流程图:


官网提供的卸载view的流程图:


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方法。

}

- (void)viewDidUnload

{

    // 被release的对象必须是在 viewDidLoad中能重新创建的对象

    // For example:

       self.myOutlet = nil;

    self.tableView = nil;

    dataArray = nil;

  

    [super viewDidUnload];

}

以上是 解析iOS内存不足时的警告以及处理过程 的全部内容, 来源链接: utcz.com/z/352315.html

回到顶部