【问题标题】:Saving model into Userdefaults crashes application swift [duplicate]将模型保存到 Userdefaults 会使应用程序迅速崩溃 [重复]
【发布时间】:2019-06-17 17:52:50
【问题描述】:

我正在尝试将我的模型类保存在 UserDefault 中,但不断收到错误 -[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x2825fc0a0'

我正在使用可编码,下面是我的模型的样子

struct AuthModel: Codable {
    let token: String?
    let firstName: String?
    let lastName: String?
    let telephone: String?
    let userId: Int?
    let email: String?
    let isEmailConfirmed: Int?
    let isVerified: Int?

    enum AuthModelCodingKeys: String, CodingKey {
        case token
        case firstName = "first_name"
        case lastName = "last_name"
        case telephone
        case userId = "user_id"
        case email
        case isEmailConfirmed = "is_email_confirmed"
        case isVerified = "is_verified"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: AuthModelCodingKeys.self)
        token = try container.decodeIfPresent(String.self, forKey: .token)
        firstName = try container.decodeIfPresent(String.self, forKey: .firstName)
        lastName = try container.decodeIfPresent(String.self, forKey: .lastName)
        telephone = try container.decodeIfPresent(String.self, forKey: .telephone)
        userId = try container.decodeIfPresent(Int.self, forKey: .userId)
        email = try container.decodeIfPresent(String.self, forKey: .email)
        isEmailConfirmed = try container.decodeIfPresent(Int.self, forKey: .isEmailConfirmed)
        isVerified = try container.decodeIfPresent(Int.self, forKey: .isVerified)
    }
}

上面的模型显示了我试图在我的 UserDefault 中保存的内容,但是当它尝试保存它时,我总是遇到崩溃。

我使用我的用户默认值如下

public func saveCurrentUser(_ user: AuthModel) {
        put(user, forKey: userKey)
    }

    private func put(_ value: Any?, forKey key: String) {
        guard let value = value else {
            storage.removeObject(forKey: key)
            return
        }
        storage.setValue(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
    }

【问题讨论】:

  • CodableNSCoding 是两个完全不相关的独立概念。
  • 我正在使用Codable
  • 这就是我的观点。 CodingNSKeyedArchiver 的使用完全无关。您正在尝试混合两种不相关的序列化方法。
  • 我该如何解决这个问题

标签: swift codable userdefaults


【解决方案1】:

使用 JSONEncoder()user 编码为data。然后使用相关的key 将这个data 保存到UserDefaults

public func saveCurrentUser(_ user: AuthModel) {
    do {
        let data = try JSONEncoder().encode(user)
        UserDefaults.standard.set(data, forKey: userKey)
    } catch  {
        print(error)
    }
}

【讨论】:

  • 我还存储了一些字符串值
  • 你在说什么字符串值?
  • 如果答案对您有帮助,请接受并投票。快乐编码..?
  • 是的。干杯@PGDev
  • 我正在尝试获取已保存的用户,但我得到了一个零返回任何帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多