如何保存实现Codable的自定义对象 [英] How to save custom objects that implements Codable

查看:317
本文介绍了如何保存实现Codable的自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,Swift 4可以更轻松地对 JSON或属性列表<进行编码/解码/ a>。

It's now easier with Swift 4 to encode / decode to and from JSON or Properties list.

但是我找不到如何使用Codable对数据进行编码,而不使用Objective-C方法 initWithCoder encodeWithCoder

But I can't find how to encode to Data using Codable, without using Objective-C methods initWithCoder and encodeWithCoder.

考虑这个简单的类:

struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}

如何使用 CodingKeys 将其编码为数据而不是 initWithCoder encodeWithCoder

How can I encode it to Data using CodingKeys and not initWithCoder and encodeWithCoder?

编辑:
我还需要能够使用NSKeyedArchiver对以前保存在userdefaults中的对象进行反序列化。

I also need to be able to deserialize objects previously saved in userdefaults using NSKeyedArchiver.

推荐答案

嗯,你不再需要 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)
}

这篇关于如何保存实现Codable的自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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