2013-11-28 31 views
1

我使用以下鏈接瞭解保留數。
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的價值。

請幫幫我。
謝謝。

+0

爲什麼要減號。哪裏不對? – ilesh

+1

閱讀您鏈接的問題的答案。他們也是你的問題的答案。 –

+0

@KurtRevis我讀了這個答案,但我不明白51它應該是2或1. – ilesh

回答

4

有關何時和爲什麼使用retainCount的說明,請參閱WhenToUseRetainCount.com

由於空數組的實現細節,計數爲51。它會變爲1,因爲您正在計算不同的對象。

如果使用手動保持釋放,那麼這個模式是一個泄漏:

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

分配的對象被泄漏。

使用ARC。