简体   繁体   中英

How to solve this memory leak (iPhone)?

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;

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];

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.

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]];
-(void )dealloc
  {
   if(self.Moins1!=nil)
     {
      self.Moins1 = nil;
     }
   }

see when u give and object a retain property its count is already 1 and when u allocate it its count becomes 2 so when the dealloc is called it will check if its nil and if its not nil make it nil .In this way it will give the retain count of the variable to 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM