xcode 当我在 Swift 中销毁我的对象时,它不会释放我的 RAM 内存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26208739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When i destroy my object in Swift it doesnt free my RAM memory
提问by Josip Bogdan
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).
这是一个测试,一个创建和销毁对象的操作,但是当我销毁它时,我的 RAM 仍在使用相同数量的内存(大约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
}
回答by Rob Napier
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.
UIImage(named:)
缓存图像。在您收到内存警告之前,这些不会被释放。也就是说,它们会在那时自动释放,即使您的应用程序在后台(通常,如果您在后台发出警告,您就没有机会减少内存)。缓存使用NSPurgableData
,这就是它可以执行此操作的原因。缓存清除非常聪明。它将清除数据,但保留文件信息,因此下次访问图像时,它会自动重新加载,您永远不会注意到图像已从内存中清除(除了小的加载延迟) . iOS 也可能会在未显示的任何时候卸载缓存的图像,但我不知道有任何文档可以准确解释何时会发生这种情况。
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.
如果您有可能再次需要此图像,则应将其保留在缓存中。从磁盘读取是昂贵的,Apple 为您提供缓存以帮助您避免该成本。但是,如果您不太可能再次显示此图像,则可以通过使用UIImage(contentsOfFile:)
来避免缓存。那不会缓存图像。尽管 Apple 会为您清除缓存,但最好避免创建不必要的内存警告。