Upload new images to UIImageView, memory from previous images not released

My application has a view with three UIImageViews . There are about 150 images as resource files, each of which is about. The application will show all images, but only three at a time.

But every time I click the button to upload three more images to UIImageViews , the Total Byte column in the Tools increases by about 700K until I get a low memory warning and then the application crashes. Somehow, the memory that I use for each download of three images is not freed.

I searched googled and tried my best to do it, but without success, and I need help.

I tried this: (This code is part of the action for loading three more images. Three ImageViews are imgShownLeft , imgShownMiddle and imgShownRight . These are instance variables. currentImage in all three UIImageViews , and then put previousImage in left and nextImage to the right:

 NSString *strImageToSet = [[imgNamesArray objectAtIndex:currentImage] stringByAppendingFormat:@".jpg"]; UIImage *img = [UIImage imageNamed:strImageToSet]; [imgShownMiddle setImage:img]; [imgShownLeft setImage:img]; [imgShownRight setImage:img]; NSString *strPreviousImage = [[imgNamesArray objectAtIndex:previousImage] stringByAppendingFormat:@".jpg"]; img = [UIImage imageNamed:strPreviousImage]; [imgShownLeft setImage:img]; NSString *strNextImage = [[imgNamesArray objectAtIndex:nextImage] stringByAppendingFormat:@".jpg"]; img = [UIImage imageNamed:strNextImage]; [imgShownRight setImage:img]; 

Then I tried this: instead of:

  UIImage *img = [UIImage imageNamed:strImageToSet]; 

I used:

  UIImage *img = [[UIImage alloc] initWithContentsOfFile:strImageToSet]; 

and assigned img to UIImageViews in the same way, followed by [img release];

Then I tried:

  UIImage *img = [[[UIImage alloc] initWithContentsOfFile:strImageToSet] autorelease]; 

Then I tried:

  img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imgNamesArray objectAtIndex:currentImage] ofType:@"jpg"]]; 

But in each case, the memory requirements grew with each run of this action.

I know that you can store three images at the same time without storing 150 images in memory! What am I doing wrong?

Thank you for understanding. / SD

+4
source share
1 answer

I think you want to use

 img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imgNamesArray objectAtIndex:currentImage] ofType:@"jpg"]]; 

to do your loading (because UIImage imageNamed: supposedly does some caching that you don't want) and then add

 [img release]; 

after each call to setImage , because the subview must be a retain image, so you skip the reference count.

I would think that the second version with autorelease would work correctly, but to be honest, the memory management rules still scare me even when I'm sure I know what I'm doing.

-1
source

All Articles