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

标签 swift codable userdefaults

<分区>

我试图将我的模型类保存在 UserDefault 中,但不断出现错误 -[__SwiftValue encodeWithCoder:]: 无法识别的选择器发送到实例 0x2825fc0a0'

我正在使用 codables,下面是我的模型的样子

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)
    }

最佳答案

使用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)
    }
}

关于swift - 将模型保存到 Userdefaults 中会使应用程序 swift 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56636494/

相关文章:

objective-c - Obj-C 到 Swift3 的类返回方法

swift - 符合 Swift 中 CaseIterable 协议(protocol)的枚举中的案例顺序?

ios - 如何在 DataProvider 类 Alamofire 函数 swift 中设置协议(protocol)函数未正确调用

多个文件中具有 Codable 的属性包装器的 Swift 编译错误

ios - 在 iOS 8 共享扩展和主应用程序之间共享数据

swift - NSURLCredential 无法在 Swift 中编译

swift - Swift 4 中 Codable 协议(protocol)的自定义字典编码器和解码器

swift - 使用 Generics/Codable w/API 响应 204 NO CONTENT

ios - 用户默认值未给出值

ios - 将值附加到数据数组并保存在 Userdefault swift 中