iOS 真机模拟内存警告

作者: 石虎132 | 来源:发表于2018-02-04 10:48 被阅读305次

//联系人:石虎 QQ:1224614774 昵称:嗡嘛呢叭咪哄

一、概念

1.内存警告原理

*iphone下每个app可用的内存是被限制的,如果一个app使用的内存超过20M,则系统会向该app发送Memory Warning消息。收到此消息后,app必须正确处理,否则可能出错或者出现内存泄露。

 *app收到Memory Warning后会调用:UIApplication::didReceiveMemoryWarning -> UIApplicationDelegate::applicationDidReceiveMemoryWarning,然后调用当前所有的viewController进行处理。因此处理的主要工作是在viewController。

 * 当我们的程序在第一次收到内存不足警告时,应该释放一些不用的资源,以节省部分内存。否则,当内存不足情形依然存在,ios再次向我们程序发出内存不足的警告时,我们的程序将会被iOS kill掉。

*苹果给每个应用程序设置20M的内存警告量,30M的闪退量,游戏会略微放款10~20M,需要向系统申请。

2.实现内存警告有三种方法。

第一种:模拟器菜单:Hardware —> Simulate Memory Warning

第二种:用程序的方法实现,只需要一句代码:

CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), (CFStringRef)@"UISimulatedMemoryWarningNotification",NULL,NULL,true);

  第三种:这是私有的 API 方法:

 SEL memoryWarningSel = @selector(_performMemoryWarning);

  if ([[UIApplication sharedApplication] respondsToSelector:memoryWarningSel]) {

      [[UIApplication sharedApplication] performSelector:memoryWarningSel];

  }else {

      NSLog(@"%@",@"Whoops UIApplication no loger responds to -_performMemoryWarning");

  }

或者:

 iOS中使用代码模拟内存警告

  [[UIApplication sharedApplication] performSelector:@selector(_performMemoryWarning)];

注意:最好只在测试的时候使用,发布到App Store的时候不要将上面的代码编译进去,使用这种没有文档化的方法有可能导致审核不通过,或者根本无法上传。

二、宏控制内存警告测试

1.开关宏

#ifndef __OPTIMIZE__

#define OPEN_MEMORY_WARNING_TEST  YES//打开内存警告测试开关

#endif

2.调用私有API

- (void)simulateMemoryWarning

  {

     if (OPEN_MEMORY_WARNING_TEST == NO) {

return;

         }

        [[UIApplication sharedApplication] _performMemoryWarning];

  }

3.在需要的地方调用

  [[MemoryWarningTest sharedInstance] simulateMemoryWarning];

谢谢!!!

相关文章

网友评论

本文标题:iOS 真机模拟内存警告

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