2011/12/11

Avoid Excessive Retaining Mistake

When I ran "Analyze" on my project, I got a lot of "potential leak" warnings. I thought I was carefully managing object retaining but I did stupid mistakes everywhere.

part of the sample header file
@property (nonatomic, retain) ClassA objA;

part of the sample source file
@synthesize objA;
...
self.objA = [[ClassA alloc] init];
...
// done using objA instance
[self.objA release];

Above example seems good and there is no places for mistake. But actually retaining is happened twice.

  • objA has "retain" attribute
  • it will retain anything with assigning operator ("=")
  • "alloc" method will increase retain count too

    Corrected code
    Class *tmpA = [[ClassA alloc] init];
    self.objA = tmpA;
    [tmpA release];
    ...
    // done using objA instance
    [self.objA release];
    

    No comments:

    Post a Comment

    Labels

    Followers