【问题标题】:Does ARC ever inject unconventional code?ARC 是否曾经注入非常规代码?
【发布时间】:2012-08-31 01:24:56
【问题描述】:
ARC 是否曾经注入过在非 ARC 环境中通常看不到的保留和释放调用?
例如,从 getter 中显式释放对象:
- (NSArray *)dummyArray {
return [[NSArray alloc]init];
}
- (void)useDummyArray {
NSArray * arr = [self dummyArray];
//do something with arr
[arr release]; //unconventional injection of release.
}
ARC 会像上面的代码那样生成释放语句,还是会自动释放 [self dummyArray] 返回的数组;
【问题讨论】:
标签:
objective-c
automatic-ref-counting
【解决方案1】:
ARC 的美妙之处在于您不知道或需要知道。但是,您可以给 ARC 静态分析器提示:
-(NSArray *) dummyArray NS_RETURNS_RETAINED { // this tells ARC that this function returns a retained value that should be released by the callee
return [[NSArray alloc] init];
}
-(NSArray *) otherDummyArray NS_RETURNS_NOT_RETAINED { // this tells ARC that the function returns a non-retained (autoreleased) value, which should NOT be released by the callee.
return [[NSArray alloc] init];
}
但是,NS_RETURNS_NOT_RETAINED 是默认值,只要您的函数名称不以 init 开头,其中NS_RETURNS_RETAINED 成为默认值。
因此,在您的特定场景中,它几乎总是会返回 autorelease'd 值。造成这种情况的一个主要原因是支持使用非 ARC 代码进行插值,这可能会导致泄漏。