我已经整理了下面这个最小化的例子,其中Xcode(4.5.2)静态分析器似乎没有检测到泄漏,以验证我对静态分析器的一些观察:
#import <Foundation/Foundation.h>
@interface Foo : NSObject {
NSArray *array;
}
@property (nonatomic, retain) NSArray *array;
- (void)bar;
@end
@implementation Foo
@synthesize array;
- (void)bar
{
// Shouldn't the static analyzer flag this as a leak?
array = [[NSArray alloc] initWithObjects:@"hello", @"world", nil];
}
@end
int main(int argc, const char *argv[])
{
@autoreleasepool {
Foo *foo = [[Foo alloc] init];
[foo bar];
[foo bar];
[foo bar];
[foo release];
}
return 0;
}
重复调用
bar
会泄露NSArray
实例,如果我没有搞错的话。 bar
创建了一个+1保留计数的NSArray
实例,而它的名称暗示着它不应该这样做。之前分配给array
实例变量的实例泄漏了,因为它从未被释放。然而,真正让我担心的是,我在某个地方读到 ARC 基本上使用与静态分析器相同的算法。这是否意味着这段代码在 ARC 下也会泄漏?或者即使没有
__strong
限定符或相应的(strong)
属性,ARC 默认也将所有实例变量视为 strong?