如何在UIImageView.animationImages之后清除内存? [英] How to clear memory after UIImageView.animationImages?
问题描述
我创建了一个新的Xcode项目,其中只有以下内容:
- 代码从png拖入的创建UIImages数组该项目(我在将数据附加到数组时尝试了UIImage(命名:)和UIImage(contentsOfFile :))
- a UIImageView
- a按钮设置imageView.animationImages = arrayOfImages并调用imageView.startAnimating()
按下按钮并播放动画时,内存使用量增加150-200MB,具体取决于图像阵列中的图像数量。然后内存使用率保持在该水平。
设置imageView.animationImages = nil不会清除内存。我怎么能清理那个记忆?
任何建议都会有所帮助。谢谢!
1。不要隐含地缓存图像
我猜你使用的是UIImage(名为:)?
此方法缓存图像,请参阅:
正如您所看到的,内存已被回收。一切都好。
I've created a new Xcode project that has only the following:
- code creating an array of UIImages from png's dragged in to the project (I have tried both UIImage(named:) and UIImage(contentsOfFile:) when appending images to the array)
- a UIImageView
- a button which sets the imageView.animationImages = arrayOfImages and calls imageView.startAnimating()
When the button is pressed and the animation plays, the memory usage increases by 150-200MB, depending on the number of images in the image array. Then the memory usage remains at that level.
Setting imageView.animationImages = nil doesn't clear the memory. How could I go about clearing that memory?
Any suggestions would be helpful. Thanks!
1. Don't implicitely cache images
I guess you are using UIImage(named:)?
This method caches the images, see: https://developer.apple.com/documentation/uikit/uiimage/1624146-init
Apple recommends:
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.
So using 'UIImage(contentsOfFile: String)' should solve your problem. Due to the documentation you need to supply a path to the image, the image name is not sufficient, see here:
https://developer.apple.com/documentation/uikit/uiimage/1624123-imagewithcontentsoffile
There it is also mentioned:
This method does not cache the image object.
2. Don't hold references to the images
When you are loading the images into a local array make sure to empty it.
self.imageArray = []
3. Set imageView.animationImages to an empty array
self.imageArray = []
self.imageView.animationImages = self.imageArray
Quick verification of the allocations in Instruments:
As you can see the memory is reclaimed. All good.
这篇关于如何在UIImageView.animationImages之后清除内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!