【问题标题】:How to understand Retain count如何理解保留计数
【发布时间】: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.comstackoverflow.com/questions/3730804/… 或许多类似的相关答案。 - 在这种特殊情况下,[[NSArray alloc]init]可能返回一个共享实例(比较 stackoverflow.com/a/18652557/1187415),因此它的保留计数取决于已经创建了多少实例。

标签: ios objective-c memory-management


【解决方案1】:

请参阅WhenToUseRetainCount.com,了解何时以及为何使用retainCount

由于空数组的实现细节,计数为 51。它变为 1,因为您正在获取不同对象的计数。

如果使用手动保留释放,那么这种模式就是泄漏:

Foo *foo = [[Foo alloc] init];
foo = [someObject retrieveTheFooness];

分配的对象泄露了。

使用 ARC。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多