• 自动释放池


    自动释放池

    • 作用

      • 自动释放对象的
      • 所有 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.)

  • 相关阅读:
    Java-集合类汇总
    Java-ArrayList
    Java-ArrayList和Vector的区别
    Java-List
    Java-Stack
    Java-Vector
    Java-HashMap
    Java-EnumSet
    18校招借鉴
    spring的设计模式
  • 原文地址:https://www.cnblogs.com/donghaoios/p/5089765.html
Copyright © 2020-2023  润新知