我正在尝试将枚举保存到UserDefaults
,但无法成功完成,因为在do try catch中出现错误。我发现它与我的枚举有关,因为当我删除班级中的枚举时,它像以前一样正常工作。
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"
}
答案 0 :(得分:4)
您必须保存枚举的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
}