2013-10-02 59 views
1

我有一個UIView,當我初始化它已經保持數2,我不明白爲什麼,作爲一個結果,我不能removefromsuperview刪除它保留計數和removeFromSuperview

ViewController.h

@property (nonatomic, retain)FinalAlgView * drawView; 

ViewController.m

self.drawView =[[FinalAlgView alloc]init]; 

NSLog(@"the retain count 1 of drawView is %d", [self.drawView retainCount]); 
//the retain count 1 of drawView is 2 

[self.bookReader addSubview:self.drawView]; 

NSLog(@"the retain count 2 of drawView is %d", [self.drawView retainCount]); 
//the retain count 2 of drawView is 3 

[self.drawView release]; 

NSLog(@"the retain count 3 of drawView is %d", [self.drawView retainCount]); 
//the retain count 3 of drawView is 2 

[UIView animateWithDuration:0.2 
       animations:^{self.drawView.alpha = 0.0;} 
       completion:^(BOOL finished){ [self.drawView removeFromSuperview]; 
       }]; 
//do not remove 

我不使用ARC

+0

您使用ARC嗎? –

+0

只有一個答案給你的問題:http://stackoverflow.com/questions/4636146/when-to-use-retaincount/4636477#4636477 – rckoenes

回答

4

你canno t指望retainCount你會得到令人困惑的結果,最好不要使用它。

Apple

......這是非常不可能的,你可以從這個方法獲取有用的信息。

0

如null表示,不能依賴retainCount。假設你正在使用ARC,你的代碼實際上是編譯成這樣的事情:

FinalAlgView *dv = [[FinalAlgView alloc] init]; // Starts with retainCount of 1 
self.drawView = dv; // Increments the retainCount 

NSLog(@"the retain count 1 of drawView is %d", [self.drawView retainCount]); 
//the retain count 1 of drawView is 2 

... 
// do not remove 
... 
[dv release]; 

如果你不使用ARC,那麼你需要在你的第一行代碼改成這樣:

self.drawView =[[[FinalAlgView alloc]init]autorelease]; 

retainCount仍將從2開始,直到自動釋放池在runloop結束時耗盡。

+0

也使用addSubview它增加到3,那麼我如何降低它到使用removeFromSuperView? –

+0

當你調用'removeFromSuperview'時,retainCount遞減。 –

+0

但removeFrmSuperview不刪除視圖 –