Ortensia C.
Ortensia C.

Reputation: 4716

Retain Count and removeFromSuperview

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

Upvotes: 1

Views: 803

Answers (2)

Guy Kogus
Guy Kogus

Reputation: 7351

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.

Upvotes: 0

Tarek Hallak
Tarek Hallak

Reputation: 18470

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.

Upvotes: 4

Related Questions