NSCache removes all its data when app goes to background State

后端 未结 1 990
时光取名叫无心
时光取名叫无心 2021-01-12 16:51

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

相关标签:
1条回答
  • 2021-01-12 17:25

    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
    }
    
    0 讨论(0)
提交回复
热议问题