使用ARC返回自动释放的对象

Ari*_*ior 8 cocoa-touch memory-management objective-c ios5 automatic-ref-counting

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

-(NSArray *) returnListNames {

    NSArray *returnList = [NSArray arrayWithArray:myListNames];

    return (returnList);
}
Run Code Online (Sandbox Code Playgroud)

在类BI中,以这种方式在某个范围内获取该列表:

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

    NSArray *myNames = [myClassA returnListNames];  

}
Run Code Online (Sandbox Code Playgroud)

考虑到returnList使用自动释放方法分配,我如何保证我不会丢失使用ARC(我不能使用retain)的引用?我必须[[NSArray alloc] init]myNames阵列上使用吗?或者我必须使用allocon returnList而不是autorelease方法?或者我可以依靠ARC吗?还是有其他解决方案吗?

Bol*_*ock 12

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

  • 那就对了.无论您使用autorelease方法还是alloc-init,都无关紧要. (2认同)