我创建了一个只有以下内容的新 Xcode 项目:
- 从拖入项目的 png 创建 UIImage 数组的代码(我在将图像附加到数组时尝试了 UIImage(named:) 和 UIImage(contentsOfFile:))
- 一个 UIImageView
- 设置 imageView.animationImages = arrayOfImages 并调用 imageView.startAnimating() 的按钮
当按下按钮并播放动画时,内存使用量会增加 150-200MB,具体取决于图像数组中的图像数量。然后内存使用率保持在该水平。
设置 imageView.animationImages = nil 不会清除内存。我该如何清除该内存?
任何建议都会有所帮助。谢谢!
最佳答案
1。不要隐式缓存图像
我猜你正在使用 UIImage(named:)?
该方法缓存图片,见: https://developer.apple.com/documentation/uikit/uiimage/1624146-init
苹果推荐:
If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system’s cache, you should instead create your image using imageWithContentsOfFile:. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.
因此使用“UIImage(contentsOfFile: String)”应该可以解决您的问题。由于需要提供图像路径的文档,图像名称是不够的,请参见此处:
https://developer.apple.com/documentation/uikit/uiimage/1624123-imagewithcontentsoffile
那里也提到了:
This method does not cache the image object.
2。不要保留对图像的引用
当您将图像加载到本地数组时,请确保将其清空。
self.imageArray = []
3。将 imageView.animationImages 设置为空数组
self.imageArray = []
self.imageView.animationImages = self.imageArray
快速验证工具中的分配:
如您所见,内存已回收。一切顺利。
关于ios - 如何在 UIImageView.animationImages 之后清除内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668841/