当应用程序接收到内存警告的时候怎么处理?

当应用程序接收到内存警告的时候怎么处理?

答:当收到内存警告的时候,应用程序会将警告一级一级往下传递,传递顺序是UIApplication->UIWindow->rootViewController(如果有子控制器)->childViewControllers。

当控制器接收到警告之后,就会调用didReceiveMemoryWarning方法。一般会在这个方法中做几件事:

1、在iOS6之前的处理方式(见图)


当应用程序接收到内存警告的时候怎么处理?_第1张图片

2、在iOS6之后的处理方式如下:

- (void)didReceiveMemoryWarning

{

[superdidReceiveMemoryWarning];

// Add code to clean up any of your own resources that are no longer necessary.

if([self.view window] ==nil)

{

// Add code to preserve data stored in the views that might be

// needed later.

// Add code to clean up other strong references to the view in

// the view hierarchy.

self.view =nil;

}

}

1>调用父类的didReceiveMemoryWarning来确保父类的行为能够被执行。

2>清理控制器不再需要的资源

3>判断控制器的view是不是正在在窗口上显示,如果不是,先保存跟view或子view相关的数据。清空所有子控件的强引用。

4>最后设置控制器的view为nil。

你可能感兴趣的:(当应用程序接收到内存警告的时候怎么处理?)