【问题标题】:Returning autoreleased objects using ARC使用 ARC 返回自动释放的对象
【发布时间】:2011-12-18 08:03:28
【问题描述】:

假设我在 A 类中编写了下面的代码:

-(NSArray *) returnListNames {

    NSArray *returnList = [NSArray arrayWithArray:myListNames];

    return (returnList);
}

在 B 类中,我以这种方式在某个范围内获得该列表:

{
    /* Without ARC I would  retain the array returned from ClassA 
       to guarantee its reference like this:
       [[myClassA returnListNames] retain]; */

    NSArray *myNames = [myClassA returnListNames];  

}

考虑到returnList 是使用自动释放方法分配的,我如何保证使用ARC 不会丢失对它的引用(在这种情况下我不能使用retain)? 我必须在myNames 数组上使用[[NSArray alloc] init] 吗?或者我必须在returnList 上使用alloc 而不是自动释放方法?或者我可以只依靠ARC吗?还是有其他解决方案?

【问题讨论】:

    标签: objective-c cocoa-touch memory-management ios5 automatic-ref-counting


    【解决方案1】:

    ARC 将为您处理此问题,因此您可以依靠它并使用该阵列开展业务。如果它发现您需要保留myNames,它会为您添加一个保留调用,或者在您编译使用它的代码时执行它实际执行的任何其他操作。

    【讨论】:

    • 所以我可以继续使用自动释放方法来分配 *returnList ARC 将保证它的存在。对吗?
    • 没错。使用 autorelease 方法还是 alloc-init 甚至都没有关系。
    • @BoltClock 这种情况下对象什么时候释放?
    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 2011-12-12
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2013-11-29
    • 2011-06-23
    相关资源
    最近更新 更多