您不能在不符合的情况下存储类实例 NSCoding / Codable 协议
NSCoding
Codable
class UserDetail : Codable { var accountIsDeleted:Bool? // you can remove this as it's useless if the you read a nil content from user defaults that means no current account var userGUID : String? var userAge: Int? }
商店
do { let res = try JSONEncoder().encode(yourClassInstance) UserDefaults.standard.set(value:res,forKey: "somekey") } catch { print(error) }
取回
do { if let data = UserDefaults.standard.data(forKey:"somekey") { let res = try JSONDecoder().decode(UserDetail.self,from:data) } else { print("No account") } } catch { print(error) }