将字典保存到 UserDefaults [英] Save dictionary to UserDefaults

查看:45
本文介绍了将字典保存到 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")

    }

}

推荐答案

字典默认是 Codable 对象,可以使用以下扩展保存到 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆