ios - 如何在 UIImageView.animationImages 之后清除内存?

标签 ios iphone swift animation memory

我创建了一个只有以下内容的新 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

快速验证工具中的分配:

allocations in Instruments

如您所见,内存已回收。一切顺利。

关于ios - 如何在 UIImageView.animationImages 之后清除内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668841/

相关文章:

ios - Firebase:Auth.signInWithEmailAndPassword 不存在

iphone - viewWillDisappear 和 viewDidDisappear 之间存在巨大延迟

Swift 覆盖泛型 swift

ios - 如何将多张图片存储到 Parse 中的单个列?

ios - 解密 AES/GCM/PKCS5Padding iOS Swift

ios - Storyboard以反向预览显示 View Controller (Xcode 8.3.2)

ios - NSJSONSerialization - 如何正确地将 JSON 转换为 NSArray?

ios - iCarousel 仅通过用户交互向一个方向滚动

iphone - 是否有可能在 IOS 中获取从用户位置到后台特定位置的距离?

iphone - 应用程序未主动运行作业,怎么办?