iosswiftimagedownloadnscacherelaunch

Does NSCache gets automatically emptied when the app is force quitted?


I am downloading some images and save them in my cache. So far so good, but when quit my app and relaunch it, the cache seems to be empty. I do not know how to check if the cache is actually empty which is why I am asking if the cache gets automatically emptied when the app was force quitted.

let cache = NSCache<NSString, UIImage>() // cache for the downloaded images


Solution

  • 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.

    What you could do is something like:

    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 the following:

    let cache = NSCache<NSString, ImageCache>()
    

    After that you have to set the data which you cached earlier:

    let cacheImage = ImageCache()
    cacheImage.image = imageDownloaded
    self.cache.setObject(cacheImage, forKey: "yourCustomKey" as NSString)
    

    And finally retrieve the data:

    if let cachedVersion = cache.object(forKey: "yourCustomKey") {
         youImageView.image = cachedVersion.image
    }
    

    UPDATE

    This was already answered by Sharjeel Ahmad. See this link for reference.