【发布时间】:2013-12-14 01:55:09
【问题描述】:
我使用以下链接了解保留计数。
retain count in iphone
根据那个问题的输出是:
NSString *str = [[NSString alloc] initWithFormat:@"a,b,c,d"];
NSArray *anArray =[[NSArray alloc]init];
NSLog(@"Retain count: %i", [anArray retainCount]);
anArray=[str componentsSeparatedByString:@","];
NSLog(@"Retain count: %i", [anArray retainCount]);
输出
Retain count: 2
Retain count: 1
当我在示例中尝试此代码时:
NSString *str = [[NSString alloc] initWithFormat:@"a,b,c,d"];
NSArray *anArray=[[NSArray alloc]init];
NSLog(@"Retain count: %i", [anArray retainCount]);
anArray=[str componentsSeparatedByString:@","];
NSLog(@"Retain count: %i", [anArray retainCount]);
那么输出就是
Retain count: 51
Retain count: 1
我不明白为什么NSArray 的保留计数是 51,在数组中赋值后它变成 1。
我也读过
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html
http://ranga-iphone-developer.blogspot.in/2011/11/what-is-retain-count-or-reference.html
iOS about retainCount
和其他教程。但我无法理解Retain count: 51 的价值。
请帮助我。
谢谢。
【问题讨论】:
-
为什么要减号。怎么了?
-
阅读您链接的问题的答案。它们也是您问题的答案。
-
@KurtRevis 我读了那个答案,但我不明白 51 它应该是 2 或 1。
-
对象的绝对保留计数没有意义。请参阅whentouseretaincount.com、stackoverflow.com/questions/3730804/… 或许多类似的相关答案。 - 在这种特殊情况下,
[[NSArray alloc]init]可能返回一个共享实例(比较 stackoverflow.com/a/18652557/1187415),因此它的保留计数取决于已经创建了多少实例。
标签: ios objective-c memory-management