views:

309

answers:

1

Does UIImage ever removes images from its cache? Can I keep a pointer to an image I got from imageNamed: and use it as long as I like or must I always call imageNamed:?

+1  A: 

The UIImage object that is returned from imageNamed: is treated like all other objects as far a memory management goes. If you want to keep the reference to the object between method calls, you should retain it and release it when you are done to decrement the reference count.

UIImage * cachedImage;

-(void) getTheImage {
  UIImage * cachedImage = [[UImage imageNamed:@"MyImage.png"] retain];
  //Do something with the image...
}
//In some other method or dealloc
[cachedImage release];

Also, note that the UIImage class reference says:

In low-memory situations, image data may be purged from a UIImage object to free up memory on the system. This purging behavior affects only the image data stored internally by the UIImage object and not the object itself. When you attempt to draw an image whose data has been purged, the image object automatically reloads the data from its original file. This extra load step, however, may incur a small performance penalty.

Jason Jenkins