将模型保存到Userdefaults中会使应用程序崩溃

时间:2019-06-17 17:52:50

标签: swift codable userdefaults

我正在尝试将模型类保存在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)
    }

1 个答案:

答案 0 :(得分:1)

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

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