使用Swift将可编码的结构保存到UserDefaults

时间:2018-08-05 18:09:03

标签: swift codable userdefaults

我正在尝试对结构进行编码

@OneToMany(mappedBy = "course", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Review> reviews = new ArrayList<>();

public void addReview(Review review){
    review.setCourse(this);
    reviews.add(review);
}

转换为JSON以存储在UserDefaults.standard的本地密钥中。我有以下代码:

   struct Configuration : Encodable, Decodable {
    private enum CodingKeys : String, CodingKey {
        case title = "title"
        case contents = "contents"
    }
    var title : String?
    var contents: [[Int]]?
}

打印返回:

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

所以我相信我正确地创建了对象。但是,当我下次尝试运行模拟器时尝试检索密钥时,我什么也没得到。 我将以下内容放到AppDelegate中,它始终返回No Config。

jsonString = Configuration(title: Optional("config"), contents: Optional([[4, 5], [5, 5], [6, 5]]))

有什么想法吗?谢谢

3 个答案:

答案 0 :(得分:3)

这里您要保存一个Data值(正确)

defaults.set(recode, forKey: "simulationConfiguration")

但是您在这里正在阅读String

defaults.string(forKey: "simulationConfiguration")

您无法保存Data,不能阅读String并期望它能正常工作。

让我们修复您的代码

首先,您不需要手动指定编码键。所以你的结构就变成这样

struct Configuration : Codable {
    var title : String?
    var contents: [[Int]]?
}

保存

现在这是保存它的代码

let configuration = Configuration(title: "test title", contents: [[1, 2, 3]])
if let data = try? JSONEncoder().encode(configuration) {
    UserDefaults.standard.set(data, forKey: "simulationConfiguration")
}

加载

这是读取它的代码

if
    let data = UserDefaults.standard.value(forKey: "simulationConfiguration") as? Data,
    let configuration = try? JSONDecoder().decode(Configuration.self, from: data) {
    print(configuration)
}

答案 1 :(得分:0)

encode(_:)

JSONEncoder函数返回Data,而不是String。这意味着当您需要从Configuration取回UserDefaults时,需要获取数据并对其进行解码。 这是示例:

let defaults = UserDefaults.standard
guard let configData = defaults.data(forKey: "simulationConfiguration") else {
  return nil // here put something or change the control flow to if statement
}
return try? JSONDecoder().decode(Configuration.self, from: configData)

  • 您也无需为CodingKeys中的所有案例分配值,这些值自动是案例的名称
  • 如果您同时符合EncodableDecodable的要求,则可以简单地使用Codable代替,因为它是两者的组合,并且定义为typealias Codable = Encodable & Decodable

答案 2 :(得分:0)

如果您希望使用外部依赖关系来节省很多挫败感,请签出SwifterSwift

这是我使用他们的UserDefaults扩展名在两行中进行的操作。

用于设置:

UserDefaults.standard.set(object: configuration, forKey: "configuration")

用于检索对象:

guard let configuration = UserDefaults.standard.object(Configuration.self, with: "configuration") else { return }
print(configuration)

就是这样.. !!

相关问题