ios - 从内存中释放图像, swift

标签 ios swift image memory

我创建了一个应用程序,其中包含 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/

相关文章:

Python 错误 : "socket.error: [Errno 11] Resource temporarily unavailable" when sending image

css - 帮助解决 jq.imghover1.1 图像容器绝对定位问题!

ruby-on-rails - 当您不想使用图像标签时如何获取 Rails 图像路径

ios - 制作效果 上滑时顶部图片被内容覆盖

html - 滚动时在 iOS Safari 上出现奇怪的阻塞

ios - Realm - cocoa : How to add notification inside other notification block

ios - UIView socket 和 ChildViewController 之间有什么区别?

ios - 当没有看到 UIScrollView 上的 UITextField 时 resignFirstResponder

swift - 我无法让客户端脚本连接到本地主机服务器,TCP 连接永远不会发生

ios - 从不同 VC 访问时,带有完成处理程序的 API 调用函数崩溃