zoukankan      html  css  js  c++  java
  • 自动释放池

    自动释放池

    • 作用

      • 自动释放对象的
      • 所有 autorelease 的对象,在出了作用域之后,会被自动添加到最近创建的自动释放池中
      • 自动释放池被销毁或者耗尽时,会向池中所有对象发送 release 消息,释放池中对象
      • 自动释放池,在 ARC & MRC 程序中,同样有效
        • 自动释放池是什么时候创建的?什么时候销毁的?

        • 创建,运行循环检测到事件并启动后,就会创建自动释放池

        • 销毁:一次完整的运行循环结束之前,会被销毁
        • for(int i= 0 ;i<100000;i++){
              NSArray *array =[[NSArray array] autorelease];
          
              NSLog(@"%@",array);
          }
          
          • 提问:以上代码是否有问题?如果有,如何解决?

          • 解决方法:引入自动释放池

          //先定义一个自动释放池
          NSAutoreleasePool *pool=nil;
              for(int i= 0 ;i<100000;i++){
                  if (i%100==0) {
                      //先将原先的100个对象释放掉
                      [pool release];
          
                      //创建一个新的自动释放池
                      pool = [[NSAutoreleasePool alloc] init];
                  }
          
                  NSArray *array =[[[NSArray alloc] init] autorelease];
          
                  NSLog(@"%@",array);
              }
          
              [pool release];
          
          • 日常开发中,应该尽可能避免一次性创建很多个临时对象,虽说,临时对象最终会被释放,但是会造成瞬间的内存峰值,导致App闪退!

          内存释放出的使用场合

          • 如果确实需要使用内存释放池,还是得用,下面列举了哪些场合需要使用

            ◦ If you write a loop that creates many temporary objects.You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.

            ◦ If you spawn a secondary thread.You must create your own autorelease pool block as soon as the thread begins executing; otherwise, your application will leak objects. (See Autorelease Pool Blocks and Threads for details.)

  • 相关阅读:
    JSTL fn:split()函数
    JSTL判断list是否为空
    oracle 合并列的函数wm_concat
    Eclipse软件使用说明
    Caused by: org.hibernate.HibernateException: identifier of an instance of ... is alterde from
    SpringData JPA详解
    关于JPA方法名创建自动查询
    jquery移除、绑定、触发元素事件使用示例详解
    js String对象中常用方法小结(字符串操作)
    java中list的使用方法
  • 原文地址:https://www.cnblogs.com/donghaoios/p/5089765.html
Copyright © 2011-2022 走看看