tags:

views:

844

answers:

1

My app has a view with three UIImageViews. There are about 150 images as resource files, each a .jpg of about 24k. The app will show all of the images, but only three at a time.

But every time I click the button to load three more images into the UIImageViews, the "Overall Bytes" column in Instruments increases by about 700K, until I eventually get a low memory warning and then the app crashes. Somehow, the memory I use for each load of three images isn't being released.

I've googled around and tried every way I know to do this, but no success and I need help.

I've tried this: (This code is part of the action to load three more images. The three ImageViews are imgShownLeft, imgShownMiddle, and imgShownRight. Those are instance variables. I first have to put "currentImage" in all three UIImageViews, and then put "previousImage" in the left one and "nextImage" in the right one:

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 the UIImageViews 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 every case the memory requirements grew with each run of this action.

I know it's possible to keep three images loaded at a time without holding 150 images in memory! What am I doing wrong?

Thanks for any insight. /SD

A: 

I think what you want is to use

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

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

[img release];

after each setImage call, because the subviews should be retain-ing the images, so you're leaking a reference count.

I would have thought that the second version with autorelease would have worked properly, but to be honest Cocoa memory management rules still manage to confuse me even when I'm pretty sure I know what I'm doing.

David Maymudes