R – Memory management when using UIImage

cocoa-touchiphonememory-management

My application heavily uses the UIImage object to change images on a single UIImageView based on user input and the previous image which was set. I use [UIImage imageNamed:] to create my UIImage objects.

I guess this is not the best way to use UIImage coz my memory usage keeps increasing with time and never drops. (Got to know this when I ran the app with Object Allocations and moreover there are no other NSString variables I am using, only BOOL and UIImage)

How should I effectively use UIImage and UIImageView objects to keep the memory low?

Thanks

Best Answer

[UIImage imageNamed:] 

caches the image you're loading into memory. This is great if you want to reuse the same set of images over and over again, but if you are constantly showing different (or large) images, then you should use:

NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *imageData = [NSData dataWithContentsOfFile:fileLocation];

[UIImage imageWithData:imageData];

instead.