关于memory warning

来源:互联网 发布:济南淘宝代运营公司 编辑:程序博客网 时间:2024/05/16 04:28

对于IOS来说,内存使用其实是十分紧缺的。所以在开发的时候需要谨慎的进行内存管理。
系统有四种内存警告,定义如下:

    typedef enum {

    OSMemoryNotificationLevelAny      = -1,    OSMemoryNotificationLevelNormal   =  0,    OSMemoryNotificationLevelWarning  =  1,    OSMemoryNotificationLevelUrgent   =  2,    OSMemoryNotificationLevelCritical =  3

    } OSMemoryNotificationLevel;
当系统内存紧张的时候,系统会发出level1的内存警告。此时我们应该作出相应的处理。如果内存紧张没有得到解决的话,系统会在尝试多次level1警告失败的情况下发出level2的警告。一般这个阶段,系统会自动关闭我们的app来释放内存。(我是没有见识过level3,也想不明白为什么已经关闭了app还会发生level3的警告。)但是根据stack over flow上面讲的“当发生level 3警告时,系统内核将会接管,很有可能关掉IOS的主界面进程(SpringBorad),甚至会重启”。

一般情况下,对于ios有着自己的memory warning机制:当运行过程中遇到内存警告的话,程序通常情况下都先调用AppDelegate中的applicationDidReceiveMemoryWarning, 然后程序会通知各ViewController,调用其didRecieveMemoryWarning方法。

在viewController中调用didReceiveMemoryWarning方法时,如果是ios6之前,会自动调用viewDidUnLoad方法。但是鉴于现在几乎市场上不再有ios6之前的版本,这里就不深讨了。对于ios6之后,didReceiveMemoryWarning方法可以直接释放资源,不过不会释放view。需要通过以下方法释放:

-(void)didReceiveMemoryWarning    {       [super didReceiveMemoryWarning];//即使没有显示在window上,也不会自动的将self.view释放。       // Add code to clean up any of your own resources that are no longer necessary.       //需要注意的是self.isViewLoaded是必不可少的,其他方式访问视图会导致它加载 ,在WWDC视频也忽视这一点。       if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图       {            // 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;// 目的是再次进入时能够重新加载调用viewDidLoad函数。       }}
0 0