簡體   English   中英

如何將枚舉保存到 UserDefaults?

[英]How to save Enum to UserDefaults?

我正在嘗試將枚舉保存到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"
}

您必須保存枚舉的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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM