Question

I have a UIView that when I initialize it has already retain count 2 and I do not understand why, as a result I can not remove it with 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

I not use ARC

Was it helpful?

Solution

You cannot count on retainCountyou will get confusing result, and better don't use it at all.

From Apple:

... it is very unlikely that you can get useful information from this method.

OTHER TIPS

As null said, you can't rely on retainCount. Assuming that you're using ARC, your code is actually compiling to something like this:

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];

If you aren't using ARC, then you need to change your first line of code to this:

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

The retainCount will still start at 2 until the autorelease pool is drained at the end of the runloop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top