我创建了一个应用程序,其中包含 2 个嵌入了导航 Controller 的 View Controller 。第一个 View Controller 只包含一个按钮(触发 seague 到第二个 View Controller ),第二个 View Controller 只包含一个 UIImageView 和一个高分辨率图像(300MB)。当它显示第二个 View Controller 时,内存占用大约 300 MB,而我返回到第一个 View Controller (popviewcontroller),内存使用量仍然消耗 300MB。经过一些研究,我猜加载的图像仍然存储在缓存中并且没有被释放。所以我的问题是如何手动释放图像以便内存使用率下降?
已编辑 大家好,回答我自己的问题。使用“autoreleasepool”就可以了。
最佳答案
你能试试这个方法吗?如果图像太大,切勿将其放入 image xcassets 文件夹中。将它放在项目导航器中并将其用作路径。
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")
}
如果图片很大就不要这样用
imageView.image = UIImage(named: image name)
根据苹果文档App doc .它不会释放使用内存。它缓存图像以备将来使用。使用 imageWithContentsOfFile: 或者 初始化(文件内容:) 方法来创建初始数据不在包中的图像对象。这些方法每次都从磁盘加载图像数据,因此您不应该使用它们重复加载相同的图像。 如果您想了解详情 here就是答案。
关于ios - 从内存中释放图像, swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45159243/