ios - 将它们存储在 UserDefault 中时如何处理模型迁移?

标签 ios swift nsuserdefaults

我有一个名为 User 的对象,它符合 Swift4 中引入的 Codable

比如这个对象曾经是

struct User: Codable {
    var firstName: String
}

我们使用 PropertyListDecoder().decode(User.self, from: data)PropertyListEncoder().encode(value)User 进行编码 转换为 Data 并将 Data 解码为 User

现在我们将对象更新为

struct User: Codable {
    var firstName: String
    var isLoggedIn: Bool
}

如果我们的应用程序是从旧应用程序更新而来的,旧应用程序在 UserDefault 中存储了旧的 Data。更新后应用程序要做的第一件事是获取此 Data 并尝试使用 PropertyListDecoder().decode(User.self, from: data 解码为 User )。但是,它给出了一个错误:

po PropertyListDecoder().decode(User.self, from: data)
▿ DecodingError
  ▿ keyNotFound : 2 elements
    - .0 : CodingKeys(stringValue: "isLoggedIn", intValue: nil)
    ▿ .1 : Context
      - codingPath : 0 elements
      - debugDescription : "No value associated with key CodingKeys(stringValue: \"isLoggedIn\", intValue: nil) (\"isLoggedIn\")."
      - underlyingError : nil

知道在这种情况下我将如何处理模型迁移吗?我知道对于 Coredata 来说,有一些简单的方法可以解决这个问题,但我不知道如何在 UserDefault 中实现它。

最佳答案

如果没有,您可以实现解码初始化器并为 isLoggedIn 设置默认值:

struct User: Codable {
  var firstName: String
  var isLoggedIn: Bool

  enum Keys: CodingKey {
    case firstName
    case isLoggedIn
  }

  public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    firstName = try container.decode(String.self, forKey: .firstName)
    isLoggedIn = try container.decodeIfPresent(Bool.self, forKey: .isLoggedIn) ?? false
  }
}

关于ios - 将它们存储在 UserDefault 中时如何处理模型迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252033/

相关文章:

ios - 按下一个 UIButton 会触发另一个 UIButton : I don't want this to happen

swift - iPhone X、iPhone XS 等相机变焦问题

ios - 在 iOS 中保存访问 token 的最佳实践

objective-c - 为什么这个没有保存?

ios - UIWindow 类 : What's the difference between addSubview and setRootViewController

ios - View Controller 之间的共享单元格

ios - 在以模态方式从 View Controller 切换到另一个 View Controller 后,在 View Controller 上添加模糊效果

arrays - Swift - 将 UInt8 字节转换为位数组

ios - Xcode : Why doesn't this code work for saving UITextField using NSUserDefaults?

ios - LinkedIn SDK 的位码错误