iOS 如何处理内存警告

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

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

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

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

        - (void)didReceiveMemoryWarning

        {

            [super didReceiveMemoryWarning];

            // 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。

 

posted @ 2015-07-01 19:01  子涛  阅读(381)  评论(0编辑  收藏  举报