iOS 真机模拟内存警告

//联系人:石虎 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];


谢谢!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值