views:

761

answers:

3

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;
+2  A: 

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];
Dave DeLong
A: 

You should not need to send -copy to the NSData object. UIImage does not keep a reference to the data around, it just reads it and produces an image. Sending -copy without -release is a memory leak.

However, that does not explain the EXC_BAD_ACCESS. Something else is going on, and not from the code you've posted.

John Calsbeek
A: 

There are two problems in your code. The copying of imageData as indicated by the other contributers, and the assignment to Moins1 field without retaining the object.

The assingment to Moins1 access the field directly, so you would need to do your own retaining. If you don't retain it and release it in the next line, then any subsequence access to the field results into a protection error.

You can use the property for assignment:

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

Or you can also just do it in one line:

self.Moins1 = [UIImage imageWithData:[[myg.imageData copy] autorelease]];
notnoop