views:

352

answers:

2

I'm using the following code:

UIImage *buttonImage;

if (p.placeImage != nil) {
    buttonImage = [UIImage imageWithData:p.placeImage];
} else {
    buttonImage = [UIImage imageNamed:@"bg_place_noimg.png"];
}

[imageButton setBackgroundImage:buttonImage forState:UIControlStateNormal];

When executing the app with Instruments I can see the setBackgroundImage consumes a lot of memory. However, if I comment the last line it doesn't happen. Any possible reason?

EDIT:

If p.placeImage == nil and imageNamed:@"bg_place_noimg.png" is used memory usage is normal. p.placeImage is a Transformable value I use in Core Data to store images NSData downloaded from Internet.

A: 

I'm not sure, but I would guess that your problem is that imageWithData: creates a whole new image each time, whereas the imageNamed: method returns the same image over and over again.

You may need to add some code to cache and reuse images that are identical. For example, maybe you could use a URL as a key into a dictionary of images, and only create new images for URLs that have not been loaded before.

Kristopher Johnson
+1  A: 

I'm not surprised that commenting out the last line causes less memory to be consumed. When you set that image as the background of your button, the image is most likely retained by the button and so the image remains in memory. If you don't apply the image as the button background, the UIImage's retain count is 0 and so its memory can be reclaimed by the system if necessary.

Kristopher's theory about the difference between imageWithData and imageNamed is also correct. Check out the Discussion section for each of those initializers in the documentation for UIImage.

Jonathan Arbogast