// @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt Expat const ghostHost = "https://williamboles.me" // @license-end

Double retaining with a retained property

October 19th, 2011

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.

Photo of a baby holding a finger

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

William Boles

William has been an iOS developer since 2010, after all these years he just hopes that the String API will stop changing now.