我正在下载一些图像并将它们保存在我的缓存中。 到目前为止还不错,但是当退出我的应用程序并重新启动它时,缓存似乎是空的。 我不知道如何检查缓存是否实际上是空的,这就是为什么我问缓存是否会自动清空当应用程序被强制退出。
let cache=nscache
是的,它做到了,出于某种原因,当应用程序进入后台时,即使没有内存压力,它也会立即从缓存中删除数据。 要解决这个问题,您必须告诉NSCache您的数据不应该被丢弃。
你可以这样做:
class ImageCache: NSObject , NSDiscardableContent {
public var image: UIImage!
func beginContentAccess() -> Bool {
return true
}
func endContentAccess() {
}
func discardContentIfPossible() {
}
func isContentDiscarded() -> Bool {
return false
}
}
然后在NSCache中使用此类,如下所示:
let cache = NSCache<NSString, ImageCache>()
之后,您必须设置先前缓存的数据:
let cacheImage = ImageCache()
cacheImage.image = imageDownloaded
self.cache.setObject(cacheImage, forKey: "yourCustomKey" as NSString)
最后检索数据:
if let cachedVersion = cache.object(forKey: "yourCustomKey") {
youImageView.image = cachedVersion.image
}
NSCache不会将其元素持久化到磁盘上。 它只会把它们留在记忆中。 当一个应用程序被强制退出时,那么它的所有RAM将被破坏,显然在下一次启动时不能重复使用