保留计数几乎没有用,详情请参阅http://whentouseretaincounts.com。
不过,我加入呼吁retainCount
你的代码并运行以下:
NSArray *arr = [[NSArray arrayWithObjects:@"ag", @"sdfg", @"dgh", nil] retain];
NSLog(@"%ld", [arr retainCount]);
NSArray *newArr = [[arr mutableCopy] retain];
NSLog(@"%ld", [newArr retainCount]);
[arr release];
NSLog(@"%ld", [arr retainCount]);
[newArr release];
NSLog(@"%ld", [newArr retainCount]);
newArr = [NSArray arrayWithObject:@"sdfdhs"];
NSLog(@"%ld", [newArr retainCount]);
,并得到了以下结果:
2013-01-24 15:45:56.840 Untitled 2[96774:707] 2
2013-01-24 15:45:56.842 Untitled 2[96774:707] 2
2013-01-24 15:45:56.842 Untitled 2[96774:707] 1
2013-01-24 15:45:56.843 Untitled 2[96774:707] 1
2013-01-24 15:45:56.843 Untitled 2[96774:707] 1
的第一个结果是2
不1
因为返回值从arrayWithObjects
已经autoreleased但尚未实际发布,因为autorelease池尚未刷新(这通常发生在事件循环)。
第二个结果是2
,因为mutableCopy
返回了一个保留对象,我们再次retain
。
第三个结果是1
,因为我们发布arr
,其保留计数为2
。仍然没有刷新autorelease池。
第四个结果是1
,因为我们发布了newArr
,其保留计数为2
。
最终结果是1
,因为我们泄漏了newArr
的内容并为该变量分配了一个新的autoreleased数组。保留计数为1
是尚未自动发布的计数。
但是,保留计数不应被信任。了解内存管理规则(无论您是否使用ARC)。
看看http://whentouseretaincount.com – mttrb
好吧,看看它自己的仪器。 –
你在采访我们吗? –