将值设置为缓存图像以崩溃结束

Set value to an cached image ends in crash

我正在下载图像并将其添加到我的缓存中。这工作正常,但是当我想在缓存中为我下载的图像添加一个值时,我的代码 returns 错误“由于未捕获的异常 'NSUnknownKeyException' 而终止应用程序,原因:'[ setValue:forUndefinedKey:]:此 class 与键 XXX 的键值编码不兼容。

 let cache = NSCache<NSString, UIImage>()

 func downloadImage(withURL url:URL, completion: @escaping (_ image:UIImage?)->()) {
        let dataTask = URLSession.shared.dataTask(with: url) { data, responseURL, error in

            var downloadedImage:UIImage?

            if let data = data {
                downloadedImage = UIImage(data: data)
                print("downloadedImage")
            }
            DispatchQueue.main.async {
                completion(downloadedImage)
            }
            if downloadedImage != nil {

                let date = Date() // calling the date
                var calendar = Calendar.current // calling the calendar
                if let timeZone = TimeZone(identifier: "GMT-4") { 
                    calendar.timeZone = timeZone
                }
                let day = calendar.component(.day, from: date)
                
                self.cache.setObject(downloadedImage!, forKey: url.absoluteString as NSString)
                self.cache.setValue(day, forKey: url.absoluteString) // this line runs into an error
            }
            
        }
        dataTask.resume()
    }

错误发生是因为 Int 不是 NSObject

的子类

但是还有另外两个严重的问题。

  1. 缓存声明为 <NSString, UIImage>,因此值必须是 UIImage,但是 dayInt
  2. 无论如何用整数覆盖图像是没有意义的

您可以将 day 值附加到 URL 字符串

let day = calendar.component(.day, from: date)
let key = "\(url.absoluteString)-\(day)"            
self.cache.setObject(downloadedImage!, forKey: key as NSString)