I am working with NSCache
, I am using NSCache
to store images. I am showing images on UITableView
. Whenever I add images first they ar
Yes it does that, for some reason it instantly removes data from cache when app enters background even if there is no memory pressure. To fix this you have to tell NSCache
that your data should not be discarded.
Here is how you fix this.
class ImageCache: NSObject , NSDiscardableContent {
public var image: UIImage!
func beginContentAccess() -> Bool {
return true
}
func endContentAccess() {
}
func discardContentIfPossible() {
}
func isContentDiscarded() -> Bool {
return false
}
}
and then use this class in NSCache
like this.
let cache = NSCache<NSString, ImageCache>()
and then set the data in cache like this
let cacheImage = ImageCache()
cacheImage.image = imageDownloaded
self.cache.setObject(cacheImage, forKey: "somekey" as NSString)
and to retrive the data
if let cachedVersion = cache.object(forKey: "somekey") {
youImageView.image = cachedVersion.image
}