现在使用 Swift 4 可以更轻松地对 JSON or Properties list 进行编码/解码.
但我找不到如何使用 Codable 编码数据,而不使用 Objective-C 方法 initWithCoder
和 encodeWithCoder
。
考虑这个简单的类:
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
如何使用 CodingKeys
而不是 initWithCoder
和 encodeWithCoder
将其编码为数据?
编辑: 我还需要能够使用 NSKeyedArchiver 反序列化以前保存在 userdefaults 中的对象。
最佳答案
嗯,你不再需要 NSKeyedArchiver
。
试试这个:
let questionObj = Question(title: "WWDC, 2017", answer: 1,question:1)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(questionObj) {
UserDefaults.standard.set(encoded, forKey: "K_Question")
}
let decoder = JSONDecoder()
if let questionData = UserDefaults.standard.data(forKey: "K_Question"),
let question = try? decoder.decode(Question.self, from: questionData) {
print(question.title)
print(question.answer)
print(question.question)
}
关于ios - 如何保存实现 Codable 的自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44495842/