我正在下载图像并将其添加到我的缓存中。这很好,但是当我想在缓存中为我下载的图像添加一个值时,我的代码返回错误“由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[<NSCache 0x600001cfa3c0> setValue:forUndefinedKey:]:此类不符合键 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()
}