2013-10-02 56 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不删除视图 –