Ethan Allen
Ethan Allen

Reputation: 14835

How do I properly handle a memory warning in the UIPickerViewController for my UIImageView with an image in it?

So I have a UIImageView on a view. The view also has a button on it to pop a UIPickerViewController or camera controls. When someone selects an image, it sets the myImageView.image property and displays the image in my view. No saving of the image is done... it's just a display of what you've chosen.

Sometimes, when I'm in UIPickerViewController, I get a memory warning. Because the picker is open, all of the other non-visble views, including my UIImageView, get released and viewDidLoad gets called again when the picker closes. This is as expected. But in the process I lose the image I was displaying as the image reverts back to it's original "choose an image" image placeholder.

But how do I load the image that was in the UIImageView BEFORE the memory warning back into the UIImageView? Since it was in memory, it's now lost. And I don't know it's location because the user picked it from the picker and I just took it straight from there with this:

itemImageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];

Any ideas on how to recover that lost image? Or if I should save it in some variable or to the device to use again in case of a memory warning??

Upvotes: 1

Views: 423

Answers (2)

Rob B
Rob B

Reputation: 1485

You need to retain a reference to the image as well as showing it in the UIImageView. e.g. save it in a property called selectedImage:

.h:

@property (nonatomic, retain) UIImage* selectedImage;

Image picker delegate:

self.selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
itemImageView.image = selectedImage;

Then when itemImageView is unloaded (along with the rest of the view) due to low memory, you will still have the image retained. In viewDidLoad, check to see if you have an image that you should show:

if (selectedImage != nil)
    itemImageView.image = selectedImage;

Make sure you release selectedImage when it's appropriate to do so for your app - e.g. when the user progresses beyond this screen, or when they cancel selecting this image, or when you save it out to the file system etc.

Upvotes: 1

Ilanchezhian
Ilanchezhian

Reputation: 17478

Yes, it would be better if you have a variable for the image and retaining the image.

Upvotes: 0

Related Questions