The method returns an Objective-C object with the preservation of the number +1

Since upgrading to Lion and therefore Xcode 4.1

When I start the analyzer, I get dozens of "potential memory leaks."

I would usually use a property list as follows:

@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 the dealloc () method:

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

Now, the analysis will show me a scary blue message on self.indexPath that says there is a leak. When obviously not.

How do you isolate and format your code so that Xcode doesn't consider it a leak? (saving property alias self.var vs _var)

Thank...

+5
source share
5 answers

Other answers already explain the problem in detail, 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:...];
+8

init ivars :

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

, ? .

+6

, setter , , , ivar. , setter , .

, , self.indexPath == _indexPath, , , init. , , , .

, , release , . :

NSIndexPath *tmpPath = [[NSIndexPath alloc] init];
self.indexPath = tmpPath;

[tmpPath release];           // This is the only correct way to do it.
// [self.indexPath release]; // WRONG! May not be the same object as tmpPath
// [_indexPath release];     // WRONG! May not be the same object as tmpPath

, init ivar . :

_indexPath = [[NSIndexPath alloc] init];
+4

:

NSIndexPath *tmpPath = [[NSIndexPath alloc] init];
self.indexPath = tmpPath;
[tmpPath release];
+2

, , , , , .

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

. ,

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

+1

[[NSIndexPath alloc] init]

, self.indexPath

[self setIndexPath:[[NSIndexPath alloc] init]];

( @synthesize), , :

- (void)setIndexPathL(NSIndexPath *)indexPath
{
    if (_indexPath != indexPath) {
        [_indexPath release];
        _indexPath = [indexPath retain];
    }
}

So, now the analyzer sees that there is another one on indexPath retain.

So, to save 2 x +1, and you can only assume that you unlock once in dealloc.

+2
source

All Articles