自动释放池

自动释放池

  • 作用

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

转载于:https://www.cnblogs.com/donghaoios/p/5089765.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值