本文介绍了将字典保存到UserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字典存储在UserDefaults中,并在代码运行时始终使应用程序崩溃.这是在执行应用程序时使应用程序崩溃的示例代码.我试图将其强制转换为NSDictionary或将其最初转换为NSDictionary-得到了相同的结果.

I'm trying to store a dictionary in UserDefaults and always get app crash when the code runs. Here is the sample code which crashes the app when it is executed. I tried to cast it as NSDictionary or make it NSDictionary initially - got the same result.

class CourseVC: UIViewController {

let test = [1:"me"]

override func viewDidLoad() {
    super.viewDidLoad()

    defaults.set(test, forKey: "dict1")

    }

}

推荐答案

默认情况下,字典是可编码对象,您可以使用以下扩展名将它们保存为UserDefaults

Dictionaries are Codable objects by default, you can use the following extensions to save them to UserDefaults

extension UserDefaults {
    func object<T: Codable>(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
        guard let data = self.value(forKey: key) as? Data else { return nil }
        return try? decoder.decode(type.self, from: data)
    }

    func set<T: Codable>(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {
        let data = try? encoder.encode(object)
        self.set(data, forKey: key)
    }
}

它们可以像这样使用:

let test = [1:"me"]
UserDefaults.standard.set(object: test, forKey: "test")

let testFromDefaults = UserDefaults.standard.object([Int: String].self, with: "test")

此扩展名和许多其他扩展名是 SwifterSwift 的一部分,您可能想在下一个iOS中使用它项目:)

This extension and many others are part of SwifterSwift, you might want to use it for your next iOS project :)

这篇关于将字典保存到UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-06 00:43