Mike Deluca
Mike Deluca

Reputation: 1210

iPhone app memory leak with UIImages in NSMutableArray

I have an NSMutableArray that contains images. I then have an image view that displays images from that array. However, I am getting a big memory leak each time it loads the image view. I am not sure how to correct that. I am using ARC in Xcode 5.0.2.

_image1 = [UIImage imageNamed:@"FirstImage.png"];

imagearray = [[NSMutableArray alloc] init];

[imagearray addObject:_image1];

_imageview1 setImage:[imagearray objectAtIndex:0]];

Upvotes: 0

Views: 959

Answers (2)

Sudershan shastri
Sudershan shastri

Reputation: 720

The memory leak issue might be due to the UIImage not getting nil. For that, you have to initialize UIImage with alloc and after adding it to the array, make it nil. You can prevent you memory leak in this way:

UIImage *image1 =[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"FirstImage" ofType:@"png"]];
[imagearray addObject:image1];
_imageview1 setImage:[imagearray objectAtIndex:0]];
image1 =nil;

Please let me kniw if it works. Thanks :)

Upvotes: 4

Vlad
Vlad

Reputation: 3366

From apple doc: + (UIImage)imageNamed: method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system’s cache, you should instead create your image using imageWithContentsOfFile:. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.

So as a suggestion, if you replace the imageNamed: with imageWithContentsOfFile: to avoid caching, your memory footprint should improve

Upvotes: 1

Related Questions