1

我有一个 UIView,当我初始化它时,它已经保留了计数 2,我不明白为什么,因此我无法使用 removefromsuperview 删除它

视图控制器.h

  @property (nonatomic, retain)FinalAlgView * drawView;

视图控制器.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

4

2 回答 2

4

你不能指望retainCount你会得到令人困惑的结果,最好不要使用它。

来自苹果

...您不太可能从这种方法中获得有用的信息

于 2013-10-02T08:00:58.423 回答
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 结束时自动释放池被耗尽。

于 2013-10-02T08:08:05.210 回答