保留计数并删除SuperSuperview

时间:2013-10-02 07:50:03

标签: ios uiview release-management retaincount

我有一个UIView,当我初始化它已经保留计数2,我不明白为什么,因此我无法删除它与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

2 个答案:

答案 0 :(得分:4)

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

来自Apple

  

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

答案 1 :(得分: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结束时耗尽。

相关问题