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