简体   繁体   中英

release images from memory, swift

i have created one app with 2 viewcontroller embed with navigation controller. the 1st view controller only consist of one button(to trigger seague to 2nd view controller) and 2nd view controller consist only one UIImageView with one high resolution image(300MB). When it is showing 2nd view controller the memory tooks around 300 MB and i return to 1st view controller (popviewcontroller) the memory usage still consume 300MB. After some research i guess the image loaded is still store in the cache and it is not released. So my question is how can i manually release the image so the memory usage can goes down?

EDITED Hi all, answer to my own question.Use "autoreleasepool" would do the job.

Can you please try with this way. If the size of the image is too big never put it in image xcassets folder. Place it in project navigator and use it as path.

            if let path = Bundle.main.path(forResource: image name in string, ofType: image format like "png" or "jpg"){
                if let image = UIImage(contentsOfFile: path){
                    imageView.image = image
                }else{
                    print(" No image found")
                }
            }else{
                print("No image path found")
            }

if the size of the image is big don't use like this way

imageView.image = UIImage(named: image name)

According to apple documentation App doc . It doesn't release the use memory. It caches the image for the future use. Use the imageWithContentsOfFile: or init(contentsOfFile:) method to create an image object where the initial data is not in a bundle. These methods load the image data from disk each time, so you should not use them to load the same image repeatedly. And if you want to know details here is the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM