我正在构建一个使用一些图像的游戏,我将它们加载到UIImageViews中。通过进行一些测试,我意识到加载图像时内存会增加,但是当我从superview中删除UIImageView时,内存不会减少。
例:
- 初始记忆:50mb
- 然后我在许多UIImageViews(在UIView里面)加载一些图像
- 记忆达到约70mb
- 从superview中删除所有UIImageViews,然后删除UIView
- 记忆保持70mb
似乎加载的PNG(在这种情况下,我使用资产来存储所有这些)保留在内存/缓存中,并且只在应用关闭时“解除”。
我该如何解决这个问题?当应用程序大约70-80mb时,应用程序开始变慢,这非常令人沮丧。
答案 0 :(得分:0)
您可以使用此代码,它不会将图像存储在缓存中
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleToFill) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleToFill ) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
func downloadimageFrom(url: URL, contentMode mode: UIViewContentMode = .scaleToFill) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloadimageFrom(link: String, contentMode mode: UIViewContentMode = .scaleToFill ) {
guard let url = URL(string: link) else { return }
downloadimageFrom(url: url, contentMode: mode)
}
}