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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With