Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method returns an Objective-C object with a +1 retain count

Tags:

objective-c

Since upgrading to Lion and consequently to XCode 4.1

I get dozens of "potential memory leak" when running the Analyzer.

I would typically use a property list like so:

@synthesize indexPath = _indexPath;

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
    self = [super initWithNibName:nibName bundle:nibBundle];
    self.indexPath = [[NSIndexPath alloc] init];
    [_indexPath release];
    return self;
}

and in dealloc() method:

- (void)dealloc {
    [_indexPath release];
    [super dealloc];
}

Now, analyze will show me the dreaded blue message on self.indexPath telling me that there's a leak. When there's obviously none.

How do you allocate and format your code so XCode doesn't believe it's leaking? (while keeping the property alias self.var vs _var)

Thank you...

like image 523
jyavenard Avatar asked Jul 30 '11 23:07

jyavenard


1 Answers

The other answers already explain the problem in depth, anyway these are some common patterns that you can use to avoid this error:

NSIndexPath *ip = [[NSIndexPath alloc] init];
self.indexPath = ip;
/* ... */
[ip release];

indexPath = [[NSIndexPath alloc] init];

self.indexPath = [[[NSIndexPath alloc] init] autorelease];

self.indexPath = [NSIndexPath indexPathWithIndex:...];
like image 89
3 revs Avatar answered Sep 23 '22 20:09

3 revs