ConanTheLibrarian
ConanTheLibrarian

Reputation: 1

How do I release cached images when using UIImage(data:)?

I'm noticing heavy memory usage from my image cache in my collection view and need to understand how to release it. I understand the difference between UIImage(named:) and UIImage(contentsOfFile:). However, I'm using UIImage(data:) and I can't seem to find any documentation on releasing image caches in this instance. Any help appreciated. Here's my code snippet:

if let setImage = cell?.viewWithTag(101) as? UIImageView {
    if let url = URL(string: imageURLs[indexPath.item]) {
        let task = URLSession.shared.dataTask(with: url, completionHandler: { data, _, error in
            guard let data = data, error == nil else {
                print("No data detected: \(Error.self)")
                return
            }
            DispatchQueue.main.async {
                let newImageData = UIImage(data: data)

                self.imageData[indexPath.item] = newImageData!
                setImage.image = self.imageData[indexPath.item] as? UIImage
            }
        })
        task.resume()
        URLSession.shared.finishTasksAndInvalidate()
    }
}

Upvotes: 0

Views: 1078

Answers (2)

ConanTheLibrarian
ConanTheLibrarian

Reputation: 1

I was under the impression that Firestore auto-caching applied to cloud Storage, but it only applies to cloud Database. Once I implemented local caching with NSCache, my problem was solved.

Upvotes: 0

Rob
Rob

Reputation: 437592

UIImage(data:) doesn’t store in the system image cache. So, if you remove all of the references to the associated images from your imageData, make sure the image views are getting released, etc., you should be good.

If imageData a simple collection, consider making it a NSCache, where you can constrain the total count or cost. Also, we often employ two tier caching mechanisms (with smaller in-memory limits, larger persistent storage caches).

You might consider using one of the many third party libraries (AlamofireImage, KingFisher, SDWebImage, etc.) as they tend to employ decent caching strategies, getting you out of the weeds of this. They all offer nice “asynchronous image” extensions to UIImageView, too. (For example, the implementation you’ve shared with us is going to suffer from backlogging issues if you scroll quickly through a big collection view, something that is easily tackled with these UIImageView extensions.) Your UICollectionViewDataSource really should not be burdened with this sort of code.

Upvotes: 1

Related Questions