How to clear an image from RAM memory

Viewed 1579

Every time I call the changeImage function the img image will change. The problem is that the RAM memory used by the app will increase every time the photo is changed, even if the previous photo is no longer on the screen.

enter code here import UIKit
class ViewController: UIViewController {

    var takenImage = UIImage()

    @IBOutlet var img: UIImageView!
    @IBOutlet var buton: UIButton!

    var index = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func changeImage(_ sender: Any) {
        index+=1

        switch(index) {
          case 1:  img.image = UIImage(named: "i1")
          case 2:  img.image = UIImage(named: "i2")
          case 3:  img.image = UIImage(named: "i3")
          case 4:  img.image = UIImage(named: "i4")
          case 5:  img.image = UIImage(named: "i5")
          case 6:  img.image = UIImage(named: "i6")

          default: print("default");
        }
    }
}

I expect to delete the old photos from the RAM memory

2 Answers

UImage(named:) caches the images (keeps them in memory to improve performance should you use them again). They won’t be removed from memory unless there is memory pressure.

As the documentation says:

Discussion

This method looks in the system caches for an image object with the specified name and returns the variant of that image that is best suited for the main screen. If a matching image object is not already in the cache, this method locates and loads the image data from disk or from an available asset catalog, and then returns the resulting object.

The system may purge cached image data at any time to free up memory. Purging occurs only for images that are in the cache but are not currently being used.

...

Special Considerations

If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system’s cache, you should instead create your image using imageWithContentsOfFile:. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.

Bottom line, if this is an image that you will repeatedly use in your app, you may choose to go ahead and use UIImage(named:), confident that if there is memory pressure, the images will be released. But if this is not an image that you will use repeatedly, consider using UIImage(contentsOfFile:) instead.

Agreed with @Rob's answer,

Just one improvement on the redundant code, no need to use switch-case instead you can use,

@IBAction func changeImage(_ sender: Any) {
    index += 1
    img.image = UIImage(named: "i\(index)")
}
Related