使用Swift将可编码的结构保存到UserDefaults [英] Saving a Codable Struct to UserDefaults with Swift
问题描述
我正在尝试对结构进行编码
I am trying to encode a struct
struct Configuration : Encodable, Decodable {
private enum CodingKeys : String, CodingKey {
case title = "title"
case contents = "contents"
}
var title : String?
var contents: [[Int]]?
}
转换为JSON以存储在UserDefaults.standard的本地密钥中.我有以下代码:
into JSON to store in a local key of UserDefaults.standard. I have the following code:
let jsonString = Configuration(title: nameField.text, contents: newContents)
let info = ["row" as String: jsonString as Configuration]
print("jsonString = \(jsonString)")
//trying to save object
let defaults = UserDefaults.standard
let recode = try! JSONEncoder().encode(jsonString)
defaults.set(recode, forKey: "simulationConfiguration")
//end of saving local
打印返回:
jsonString = Configuration(title: Optional("config"), contents: Optional([[4, 5], [5, 5], [6, 5]]))
所以我相信我正确地创建了对象.但是,当我下次尝试运行模拟器时尝试检索密钥时,我什么也没得到.我将以下内容放入AppDelegate中,它始终返回No Config.
so I believe I am creating the object correctly. However, when I try and retrieve the key the next time I run the simulator I get nothing. I put the following in AppDelegate and it always returns No Config.
let defaults = UserDefaults.standard
let config = defaults.string(forKey: "simulationConfiguration") ?? "No Config"
print("from app delegate = \(config.description)")
有什么想法吗?谢谢
推荐答案
在这里您要保存 Data
值(正确)
Here you are saving a Data
value (which is correct)
defaults.set(recode, forKey: "simulationConfiguration")
但是这里您正在阅读 String
defaults.string(forKey: "simulationConfiguration")
您无法保存数据
,无法读取 String
并期望它能正常工作.
You cannot save Data
, read String
and expect it to work.
首先,您不需要手动指定编码键.所以你的结构就变成这样
First of all you don't need to manually specify the Coding Keys. So your struct become simply this
struct Configuration : Codable {
var title : String?
var contents: [[Int]]?
}
保存
现在这是保存它的代码
Saving
Now here's the code for saving it
let configuration = Configuration(title: "test title", contents: [[1, 2, 3]])
if let data = try? JSONEncoder().encode(configuration) {
UserDefaults.standard.set(data, forKey: "simulationConfiguration")
}
加载
这是读取它的代码
Loading
And here's the code for reading it
if
let data = UserDefaults.standard.value(forKey: "simulationConfiguration") as? Data,
let configuration = try? JSONDecoder().decode(Configuration.self, from: data) {
print(configuration)
}
这篇关于使用Swift将可编码的结构保存到UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!