Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When i destroy my object in Swift it doesnt free my RAM memory

This is a test, an action to create and one to destroy an object, but when I destroy it my RAM is still using same amount of memory(around 30mb).

var missileImage: UIImageView!
weak var img: UIImage!

@IBAction func createImg(sender: AnyObject) {
    missileImage = UIImageView(frame: CGRectMake(CGFloat(arc4random() % 100), 200, 50, 30))
    img = UIImage(named: "house.jpg")
    missileImage.image = img
    missileImage.tag = 10001
    self.view.addSubview(missileImage)
}

@IBAction func destroyImg(sender: AnyObject) {
    self.view.viewWithTag(10001)?.removeFromSuperview()
    img = nil
    missileImage = nil
}
like image 573
Josip Bogdan Avatar asked Dec 01 '22 01:12

Josip Bogdan


1 Answers

UIImage(named:) caches images. These won't be released until you receive a memory warning. That said, they will automatically be released at that time, even if your app is in the background (usually you don't get a chance to reduce memory if the warning comes while you're in the background). The cache uses NSPurgableData, which is why it can do this. The cache clearing is very clever. It will get rid of the data, but leave the file information, so the next time you access the image, it'll automatically be reloaded and you'll never notice that the image was purged from memory (except for a small loading delay). iOS may also unload cached images anytime they're not being displayed, though I'm not aware of any documentation that explains precisely when that will happen.

If it's even somewhat likely that you will need this image again, you should leave it in the cache. Reading from disk is expensive, and Apple gives you the cache to help you avoid that cost. But if it is very unlikely that you will display this image again, you can avoid the cache by using UIImage(contentsOfFile:) instead. That does not cache the image. Even though Apple will clear the cache for you, it's nice to avoid creating memory warnings if they're unnecessary.

like image 90
Rob Napier Avatar answered Dec 04 '22 22:12

Rob Napier