美文网首页iOS相关
iOS: didReceiveMemoryWarning

iOS: didReceiveMemoryWarning

作者: 疯狂的向日葵 | 来源:发表于2016-03-18 13:14 被阅读1377次

    On iOS 6 and Later, a View Controller Unloads Its Own Views When Desired The default behavior for a view controller is to load its view hierarchy when the view property is first accessed and thereafter keep it in memory until the view controller is disposed of. The memory used by a view to draw itself onscreen is potentially quite large. However, the system automatically releases these expensive resources when the view is not attached to a window. The remaining memory used by most views is small enough that it is not worth it for the system to automatically purge and recreate the view hierarchy.
    You can explicitly release the view hierarchy if that additional memory is necessary for your app. Listing 4-3 overrides the didReceiveMemoryWarningmethod to accomplish this. First, is calls the superclass’s implementation to get any required default behavior. Then, it cleans up the view controller’s resources. Finally, it tests to see if the view controller’s view is not onscreen. If the view is associated with a window, then it cleans up any of the view controller’s strong references to the view and its subviews. If the views stored data that needs to be recreated, the implementation of this method should save that data before releasing any of the references to those views.

    iOS6.0及以上版本的内存警告:
    调用didReceiveMemoryWarning内调用super的didReceiveMemoryWarning调只是释放controller的resouse,不会释放view
    处理方法:

        -(void)didReceiveMemoryWarning
        {
                [super didReceiveMemoryWarning];//即使没有显示在window上,也不会自动的将self.view释放。
                // Add code to clean up any of your own resources that are no longer necessary.
    
                // 此处做兼容处理需要加上ios6.0的宏开关,保证是在6.0下使用的,6.0以前屏蔽以下代码,否则会在下面使用self.view时自动加载viewDidUnLoad
                if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
                 //需要注意的是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.
                       //清理view里所有的强引用对象。
                       self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
                 }
               }
        }
    

    View的生成流程

    2015107101638194.jpg

    View的销毁流程

    2015107101704363.jpg

    相关文章

      网友评论

        本文标题:iOS: didReceiveMemoryWarning

        本文链接:https://www.haomeiwen.com/subject/xxzclttx.html