0

我正在下载图像并将其添加到我的缓存中。这很好,但是当我想在缓存中为我下载的图像添加一个值时,我的代码返回错误“由于未捕获的异常'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()
    }
4

1 回答 1

1

发生错误是因为Int不是NSObject

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

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

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

let day = calendar.component(.day, from: date)
let key = "\(url.absoluteString)-\(day)"            
self.cache.setObject(downloadedImage!, forKey: key as NSString)
于 2020-06-21T08:09:31.180 回答