zoukankan      html  css  js  c++  java
  • ARC中的@autoreleasepool还有作用吗?

    ARC中的@autoreleasepool还有作用吗?

    QUESTION

    For the most part with ARC (Automatic Reference Counting), we don't need to think about memory management at all with Objective-C objects. It is not permitted to create NSAutoreleasePools anymore, however there is a new syntax:

    在ARC中,我们不再需要手动管理内存.ARC已经不允许你创建NSAutoreleasePools了,然而有一种新的语法格式:

    @autoreleasepool{}

    My question is, why would I ever need this when I'm not supposed to be manually releasing/autoreleasing ?

    我的问题是,为什么@autoreleasepool 可以在ARC中使用而不出错呢?

    ANSWER

    There seems to be a lot of confusion on this topic (and at least 80 people who probably are now confused about this and think they need to sprinkle @autoreleasepool around their code).

    这个主题看起来相当迷惑人(至少80人搞不清楚状况,或许他们会将@autoreleasepool从他们的代码中移除掉)

    If a project (including its dependencies) exclusively uses ARC, then @autoreleasepool never needs to be used and will do nothing useful. ARC will handle releasing objects at the correct time. For example:

    如果一个工程完全由ARC编译(包括它依赖的工程项目),那么@autoreleasepool 完全没有用处,ARC会自己管理好对象的内存释放问题,例如:

    @interfaceTesting:NSObject+(void) test;

    @end

    @implementation Testing

    -(void) dealloc
    {
      NSLog(@"dealloc");
    }

    +(void) test {
      while(true)
        NSLog(@"p = %p",[Testing new]);
    }

    @end

    displays:

    p =0x17696f80
    dealloc
    p =0x17570a90
    dealloc

    Each Testing object is deallocated as soon as the value goes out of scope, without waiting for an autorelease pool to be exited. (The same thing happens with the NSNumber example; this just lets us observe the dealloc.) ARC does not use autorelease.

    每一个Testing对象,在出了值的作用域之后都会被立马释放掉了,完全不需要有一个 autorelease 存在,ARC中使用autorelease完全没有用处.

    The reason @autoreleasepool is still allowed is for mixed ARC and non-ARC projects, which haven't yet completely transitioned to ARC.

    你之所以可以继续使用@autoreleasepool 的原因是因为如果你的工程是ARC与MRC混合的,工程中并没有完全的转换成ARC而已.

    If you call into non-ARC code, it may return an autoreleased object. In that case, the above loop would leak, since the current autorelease pool will never be exited. That's where you'd want to put an @autoreleasepool around the code block.

    如果你在MRC代码中调用了,它会给你返回一个autoreleased 的对象.在那种情形中,上面的循环就会泄露,所以,为了兼容MRC,你需要给你的相关代码添加@autoreleasepool.

    But if you've completely made the ARC transition, then forget about autoreleasepool.

    如果你的项目完全由ARC编译的,那么请忘掉这个autoreleasepool :).

  • 相关阅读:
    Html5新标签解释及用法
    时间线效果
    NHibernate数据访问层核心代码
    C#开源资源项目
    安卓开发环境搭建之最新版(So Easy!)
    WIN8相关资源汇总
    HTML5 Shiv – 让该死的IE系列支持HTML5吧
    WCF 提高传输数据性能方法之二 (数据分割)
    支付宝集成问题(.net篇)
    WCF 提高传输数据性能方法之一 (使用压缩)
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/3706630.html
Copyright © 2011-2022 走看看