lostInTransit
lostInTransit

Reputation: 70997

Memory management when using UIImage

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

Upvotes: 3

Views: 4616

Answers (2)

Bansi Hirpara
Bansi Hirpara

Reputation: 135

To manage memory with image, as per @russtyshelf said, you have to convert image file to data and translate it to image but after that you have to make image instance nil to clean cache memory. i.e in viewdidload() you have to write as:

let image = [UIImage imageWithData:imageData];

and on deinit of controller or during switching views your image must be nil i.e

image = nil

Upvotes: 0

rustyshelf
rustyshelf

Reputation: 45101

[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.

Upvotes: 11

Related Questions