Memory management when using UIImage

My application heavily uses a UIImage object to modify images on a single UIImageView based on user input and the previous image that was set. I am using [UIImage imageNamed:] to create UIImage objects.

I think this is not the best way to use UIImage, because memory usage continues to increase over time and never drops. (Got to know this when I started the application with Object Allocations and, in addition, there are no other NSString variables that I use, only BOOL and UIImage)

How to use UIImage and UIImageView objects efficiently to maintain low memory?

thanks

+3
source share
2 answers
[UIImage imageNamed:] 

caches the loaded image into memory. This is great if you want to reuse the same set of images over and over, but if you constantly show different (or large) images, you should use:

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

[UIImage imageWithData:imageData];

instead.

+11
source

To manage the memory with the image, as @russtyshelf said, you have to convert the image file to data and convert it to an image, but after that you need to make the image instance zero to clear the cache. those. in viewdidload () you should write like:

let image = [UIImage imageWithData:imageData];

and on the deinit of the controller or while switching views, your image should be zero, i.e.

image = nil
0
source

All Articles