2014-03-31 95 views
0

我正在做一些參考計數增加的工作。以下是示例。iOS - 參考計數問題

.h文件。

@property (nonatomic, retain) NSString *s1; 

.m文件

@synthesize S1;

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    s1 = [[NSString alloc] init]; 
    NSLog(@"%d",[s1 retainCount]); 

    [s1 retain]; 
    NSLog(@"%d",[s1 retainCount]); 

    [s1 copy]; 
    NSLog(@"%d",[s1 retainCount]); 
} 

當我發現引用計數,它顯示爲-1所有這些,我這個有點糊塗了,請幫助我。

+0

不要使用'retainCount'- http://stackoverflow.com/questions/4636146/when-to-use-retaincount/4636477#4636477 – Volker

+0

只是強調:千萬不要使用retainCount。幫你一個忙,並開始使用ARC。 – gnasher729

+0

[RetainCount在-1後可能是-1嗎?](http://stackoverflow.com/questions/16728133/retaincount-is-1-after-alloc) –

回答

3

它打印-1因爲你使用了錯誤的字符串格式。

由於retainCount返回NSUIngeter(即和無符號整數),你應該使用

NSLog(@"%lu", (unsigned long)myNSUInteger); 

除此之外,這是值得議論,你應該永遠依靠retainCount

請參閱When To You Retain Count

此外,從official documentation

這種方法在調試內存管理問題沒有價值的。 因爲任何數量的框架對象可能都保留了一個對象,以保持對它的引用,同時自動釋放 池可能在對象上保存任意數量的延遲發佈,它不可能是你可以從這個方法獲得有用的信息