Double retaining with a retained property
A common mistake I see over and over again in code is the accidental double retain. This happens when an object is set to a property that has the attribute retain
which results in a memory leak.
Let's look at an example of this happening:
@property (retain) UIView *doubleRetainedView;
@property (retain) UIView *singleRetainedView;
- (void) doubleRetainMethod
{
self.doubleRetainedView = [[UIView alloc] init];
}
- (void) singleRetainMethodA
{
self.singleRetainedView = [[[UIView alloc] init] autorelease];
}
- (void) singleRetainMethodB
{
UIView *localView = [[UIView alloc] init];
self.singleRetainedView = localView;
[localView release];
}
- (void) dealloc
{
[singleRetainedView release]; //retain count = 0
singleRetainedView = nil;
[doubleRetainedView release];//retain count = 1
doubleRetainedView = nil;
[super dealloc];
}
In doubleRetainMethod we are double retaining doubleRetainedView as the alloc/init sequence increases its retain count to 1 and the attribute "retain" on the property increases its retain count to 2 so when we dealloc we are actually reducing doubleRetainedView's retain count to 1
In singleRetainMethod method we avoid this double retain but letting go of a retain either through the autorelease pool or by directly calling release.
What do you think? Let me know by getting in touch on Twitter - @wibosco