Saving model into Userdefaults crashes application swift [duplicate]

China☆狼群 提交于 2019-12-24 19:25:15

问题


I am trying to save my model class in UserDefault but keep getting error of -[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x2825fc0a0'

I am using codables and below is what my Model looks like

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

The above model shows what I am trying to save in my UserDefault but I keep getting the crash when ever it tries to save this.

I use my user default as follows

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:


Use JSONEncoder() to encode user to data. Then save this data to UserDefaults using the relevant key.

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


来源:https://stackoverflow.com/questions/56636494/saving-model-into-userdefaults-crashes-application-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!