如何删除 UIImageView 的最后一张图片?

How to remove UIImageView's last image?

我有一个 UIImageView 可以根据级别更改图片。但是每次我更改它时,都会保留最后一张图像并且内存使用量不断上升。我认为 imageView 将图像堆叠在另一个图像之上。我试过在设置新图像之前设置 self.imageView.image = nil,但这似乎不起作用。我该如何正确执行此操作?

if (level == 1) {
    self.imageView.image = [UIImage imageNamed:@"1"];

} else if (level == 2) {
    self.imageView.image = [UIImage imageNamed:@"2"];

} else if (level == 3) {
    self.imageView.image = [UIImage imageNamed:@"3"];

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 Documentation

结论,使用 imageNamed 将图像添加到缓存中,最终可能会增加内存使用量。相反,使用 imageWithContentsOfFile 这样图像就不会添加到缓存中。

UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

您 运行 遇到的问题是由于调用 UIImage imageNamed 将解码后的图像数据缓存在内存中引起的。改为使用 imageWithContentsOfFile 加载图像,只有活动图像会保存在内存中。

其他答案已经说图片被系统缓存,因此它的内存没有释放。但那时候你不用担心。

如果系统觉得它需要更多内存,它就会清除缓存,有效地清除图像的内存并将其重新用于其他用途。

除非您发现严重问题,否则不要担心内存使用情况。如果是这样的话,imageNamed 可能是您最不担心的事情。

需要考虑的一般注意事项

是否使用缓存完全取决于您的用例。如果您经常显示相同的图像并将其加载到几个不同的地方,请使用缓存。如果只显示一次图像,请使用 imageWithContentsOfFile.