R – How to solve this memory leak (iPhone)

iphonememory-managementobjective cxcode

How to release this variable with no EXC_BAB_ACCESS ?

//First line create memory leak
UIImage *ImageAvatar =  [[UIImage alloc] initWithData:[myg.imageData copy]];
Moins1 = ImageAvatar;
//[ImageAvatar release]; if i release-> EXC_BAD_ACCESS

Moins1 is a menber of the interface is declared like this :

UIImage *Moins1;
...
@property (nonatomic, retain)   UIImage         *Moins1;

Best Answer

It looks like the problem isn't the UIImage, but rather the NSData. In Cocoa, any copy (or mutableCopy) method returns an object with a +1 retain count, meaning that you own it and are therefore responsible for releasing it.

In your code, you're calling -copy on myg.imageData, but never releasing it. That's a classic example of a memory leak. Here's what I would do to fix it, plus with changing your syntax a bit:

ivar:

UIImage *Moins1;
@property (nonatomic, retain) UIImage *Moins1;

implementation:

NSData * imageData = [myg.imageData copy];
UIImage * ImageAvatar = [[UIImage alloc] initWithData:imageData];
[imageData release];
[self setMoins1:ImageAvatar];
[ImageAvatar release];