【问题标题】:Getting an error when I try to store a dictionary using user defaults当我尝试使用用户默认值存储字典时出现错误
【发布时间】:2020-10-15 07:52:46
【问题描述】:

我正在下载图像并将带有整数的图像 url 添加到我的字典中。当视图即将消失时,我想使用用户默认值存储数据。不幸的是,我收到错误:“尝试插入非属性列表对象...”,如图所示。 我不明白为什么会出现此错误。

这是我用来下载图片和设置字典的代码。

var imageURLS = [Int: String]()

func downloadImage(url: URL) {
        let dataTask = URLSession.shared.dataTask(with: url) { data, responseURL, error in
            
            var downloadedImage:UIImage?

            if let data = data {
                downloadedImage = UIImage(data: data)
            }
            // if download actaully got an image
            if downloadedImage != nil {
                self.sum += 1 // increase the sum by one
                self.cache.setObject(downloadedImage!, forKey: url.absoluteString as NSString) // cache the image
                // add the sumas key
                // add the url as value to the dictionary
                self.imageURLS[self.sum] = url.absoluteString
            }
        }
        dataTask.resume()
    }

这是我存储和调用字典的代码。

override func viewWillDisappear(_ animated: Bool) {
        UserDefaults.standard.set(imageURLS, forKey: "imageUrlDictionary")
}

override func viewWillAppear(_ animated: Bool) {
        imageURLS = UserDefaults.standard.object(forKey: "imageUrlDictionary") as? [Int:String] ?? [:]
}

非常感谢您的帮助和建议!

【问题讨论】:

标签: ios swift dictionary url nsuserdefaults


【解决方案1】:

错误原因是属性列表键必须是String

您可以将 Int 值转换为 String

var imageURLS = [String: String]()

...

self.imageURLS[String(self.sum)] = url.absoluteString

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多