如何将 Enum 保存到 UserDefaults?
How to save Enum to UserDefaults?
我正在尝试将枚举保存到 UserDefaults
但无法成功,因为在 do try catch 中我收到错误。我发现它与我的枚举有关,因为当我删除 class 中的枚举时,它像以前一样正常工作。
class User: NSObject, NSCoding {
private(set) public var loginType: LoginType
// some other properties
init(name: String, username: String, email: String, profileImage: UIImage?) {
// some other inits
self.loginType = .email
}
init(name: String, username: String, telephoneNumber: String, profileImage: UIImage?) {
// some other inits
self.loginType = .telephoneNumber
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.loginType, forKey: LOGIN_TYPE_KEY)
}
required init?(coder aDecoder: NSCoder) {
self.loginType = aDecoder.decodeObject(forKey: LOGIN_TYPE_KEY) as! LoginType
}
}
这是我的枚举:
enum LoginType: String {
case email = "email"
case telephoneNumber = "telephoneNumber"
}
您必须保存枚举的 rawValue
func encode(with aCoder: NSCoder) {
aCoder.encode(self.loginType.rawValue, forKey: LOGIN_TYPE_KEY)
}
required init?(coder aDecoder: NSCoder) {
let loginRaw = aDecoder.decodeObject(forKey: LOGIN_TYPE_KEY) as! String
self.loginType = LoginType(rawValue: loginRaw)!
}
考虑使用 Codable
而不是 NSCoding
。您不需要 NSObject
的子类,并且可以直接序列化 RawRepresentable 枚举。
如果原始值与案例匹配,枚举可以声明得更短
enum LoginType: String {
case email, telephoneNumber
}
我正在尝试将枚举保存到 UserDefaults
但无法成功,因为在 do try catch 中我收到错误。我发现它与我的枚举有关,因为当我删除 class 中的枚举时,它像以前一样正常工作。
class User: NSObject, NSCoding {
private(set) public var loginType: LoginType
// some other properties
init(name: String, username: String, email: String, profileImage: UIImage?) {
// some other inits
self.loginType = .email
}
init(name: String, username: String, telephoneNumber: String, profileImage: UIImage?) {
// some other inits
self.loginType = .telephoneNumber
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.loginType, forKey: LOGIN_TYPE_KEY)
}
required init?(coder aDecoder: NSCoder) {
self.loginType = aDecoder.decodeObject(forKey: LOGIN_TYPE_KEY) as! LoginType
}
}
这是我的枚举:
enum LoginType: String {
case email = "email"
case telephoneNumber = "telephoneNumber"
}
您必须保存枚举的 rawValue
func encode(with aCoder: NSCoder) {
aCoder.encode(self.loginType.rawValue, forKey: LOGIN_TYPE_KEY)
}
required init?(coder aDecoder: NSCoder) {
let loginRaw = aDecoder.decodeObject(forKey: LOGIN_TYPE_KEY) as! String
self.loginType = LoginType(rawValue: loginRaw)!
}
考虑使用 Codable
而不是 NSCoding
。您不需要 NSObject
的子类,并且可以直接序列化 RawRepresentable 枚举。
如果原始值与案例匹配,枚举可以声明得更短
enum LoginType: String {
case email, telephoneNumber
}