iOS内存警告

作者: iOS开发小学生 | 来源:发表于2018-11-14 11:01 被阅读106次

    1.当iOS系统内存不足,会发出内存警告的通知。
    首先调用的是 AppDelegate 里重新的内存警告代理方法

     - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
     {
         NSLog(@"内存在警告时会AppDelegate中applicationDidReceiveMemoryWarning调用");
        }
    

    2.可以在控制器里注册内=内存警告的通知

    //控制器注册警告通知
    -(void) regMemoryWarning{
     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
         [center addObserver:self
            selector:@selector(handleMemoryWarning)
            name:UIApplicationDidReceiveMemoryWarningNotification
            object:nil];
    }
    //警告通知回调方法
    -(void) handleMemoryWarning
     {
          NSLog(@"ViewController中handleMemoryWarning调用");
         }
    
    //控制器自动调用的内存警告方法(如果控制器注册了内存警告通知,那么,当程序发生内存警告的时候,会优先调用通知方法,后调用控制器的)didReceiveMemoryWarning方法)。
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
        NSLog(@"viewcontroller 的didReceiveMemoryWarning调用");
    }
    
    

    总结:
    当发生内存警告的时候就会接收通知,调用通知方法,进行处理响应的事情。
    内存警告的优先级调用顺序是 AppDelegate的- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application方法 >控制器的UIApplicationDidReceiveMemoryWarningNotification通知方法>控制器的didReceiveMemoryWarning方法

    2.怎么模拟iOS内存警告呢?
    (1)真机模拟内存警告
    SEL sel = NSSelectorFromString([@"_perform" stringByAppendingString:@"MemoryWarning"]); // Private API
    assert([[UIApplication sharedApplication] respondsToSelector:sel]);
    [[UIApplication sharedApplication] performSelector:sel];

    (2)模拟器的模拟内存警告
    在好多大牛的帖子里看到的是这样的操作:模拟器菜单:Hardware-》Simulate Memory Warning
    当是我在操作的时候就是找不到后面的选项Simulate Memory Warning


    屏幕快照 2018-11-14 上午10.53.39.png

    当是我的心里一万个不爽啊!(我当时用的是Xcode9.4)
    后来我在Debug 的选项里看到了后面的 Simulate Memory Warning选择,所以我的操作是Debug-》Simulate Memory Warning


    屏幕快照 2018-11-14 上午10.57.48.png
    就是这样操作,就可以检验上面所写的当程序发生内存警告的时候,调用方法的顺序实现了。

    3.当内存发生警告的时候,我们应该做什么样的操作呢?
    (1)当我们在下载高清的图片和视频的时候,是很容易发生内存警告的,如果使用了SDWebImage框架,使用如下代码,可以有效的减少内存:
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];//清除内存中通过SDWebImage框架下载的图片,建议在收到内存警告时在调用
    (2) //在收到内存警告时,控制器里调用以下代码:

        if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
                if (self.isViewLoaded && !self.view.window){
                
                       //释放其他可复现的资源&&保存数据
                
                        self.view = nil;//目的是再次进入时能够重新加载调用viewDidLoad函数。
                
                    }        
        }
    

    iOS 给每个应用的缓存数据是 20M ,这个我也是从大量的帖子里,看到的答案,有待考证和探讨。希望大家来一起讨论和研究!

    相关文章

      网友评论

        本文标题:iOS内存警告

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