问题描述
众所周知,当使用 imageNamed:
方法加载图像时,UIImage会缓存其图像数据。
It is well known that UIImage caches its image data when the image is loaded using the imageNamed:
method.
来自Apple文档:
From apple documentation:https://developer.apple.com/documentation/uikit/uiimage/1624146-imagenamed
讨论:此方法在
系统缓存中查找指定名称为
的图像对象,并返回
对象,如果它存在。如果匹配的
图像对象不在
缓存中,则此方法从指定文件加载图像
数据缓存
它,然后返回生成的
对象。
Discussion: This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.
因此,用 imageNamed:我注意到内存使用率大幅增加,即使加载图像的控制器是dealloc后内存也一直在使用。 (至少它在我分配相同的控制器时没有再增加)
Because of that, after loading several images with imageNamed:
I noticed a large increase of memory usage and also that the memory was kept in use even after the controller that loaded the images was dealloc. (at least it didn't increase again when I alloc the same controller)
这让我想知道是否有任何方法可以在任何方式以任何方式清除UIImage使用的缓存给定应用程序生命周期的时间甚至控制一些缓存参数(例如它可以使用的最大内存)
That made me wonder if there is any way to clear the cache used by UIImage programmatically at any given time of my application lifecycle or even control some cache parameters (like the maximum memory that it can use, for example)
我知道我可以通过以下方式轻松解决此问题使用 initWithData
, imageWithData
, imageWithContentsOfFile
或任何其他初始化程序 imageNamed
,但在使用多个图像时需要此缓存行为,例如在 UITableView
内。
I know that I could easily solve this problem by using initWithData
, imageWithData
, imageWithContentsOfFile
or any other initializer instead of imageNamed
, but this cache behavior is desired when using several images, like inside a UITableView
.
有关如何实现这一目标的任何想法吗?
Any thoughts on how to accomplish that?
编辑:
经过一些回答我只是想说清楚在需要做某事和有可能做某事之间存在巨大差距。正如我所指出的,我知道操作系统会为我处理缓存,我只是想看看iOS SDK带来的限制。
After some answers I just want to make it clear that there is a huge gap between needing to do something and having the possibility to do something. As I pointed out, I know that the OS takes care of that cache for me, I am just trying to see the limitations that the iOS SDK imposes.
推荐答案
从发表的评论
如果您可以使用私有API (例如,在仅限AdHoc的应用中),请使用此从缓存中删除所有图像
If you can use private APIs (as in an AdHoc only app, for example) use this UIImage
method to remove all images from cache
[UIImage _flushSharedImageCache];
这篇关于有没有办法清除UIImage类使用的缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!