将字典保存到 UserDefaults

Save dictionary to UserDefaults(将字典保存到 UserDefaults)
本文介绍了将字典保存到 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)