我想将自定义类对象保存在userdefault中。我正在尝试这样保存它:
class func setModel<T: Hashable>(model: T, key: String) {
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: model)
UserDefaults.standard.set(encodedData, forKey: key)
UserDefaults.standard.synchronize()
}
但是应用程序在此方法的第一行崩溃,并显示错误:
NSForwarding:警告:类'DronesApp_Worker.WorkerProfileResponse'的对象0x600003944000没有实现methodSignatureForSelector:-前面有麻烦无法识别的选择器-[DronesApp_Worker.WorkerProfileResponse replacementObjectForKeyedArchiver:]
我的自定义对象类如下:
class WorkerProfileResponse: Codable, Hashable, Mappable{
static func == (lhs: WorkerProfileResponse, rhs: WorkerProfileResponse) -> Bool {
return lhs.id == rhs.id
}
override var hash: Int{
return self.id!
}
var id, is_logged_in, last_login, last_active: Int?
var username, email, mobile_number: String?
var categoryName: String?
var userCategories: [SelectedCategory]?
var userSubCategories: [SelectedSubCategory]?
var biometricToken: String?
var accessToken: AccessToken?
var userStatus: UserStatus?
var userProfile: UserProfile?
required init(map: Map) {
}
func mapping(map: Map) {
id <- map["id"]
is_logged_in <- map["is_logged_in"]
last_login <- map["last_login"]
last_active <- map["last_active"]
biometricToken <- map["biometricToken"]
username <- map["username"]
email <- map["email"]
mobile_number <- map["mobile_number"]
accessToken <- map["accessToken"]
userStatus <- map["userStatus"]
userCategories <- map["userCategories"]
userSubCategories <- map["userSubCategories"]
userProfile <- map["userProfile"]
}
}
使用JSONEncoder将数据保存到UserDefaults。虚拟代码:
class YourClassName: Codable {
//Your properties here
func saveInPreference() {
do {
let jsonEncoder = JSONEncoder()
UserDefaults.standard.set(try jsonEncoder.encode(Your object here), forKey: "Write UserDefaultKey here")
UserDefaults.standard.synchronize()
}
catch {
print(error.localizedDescription)
}
}
}
希望有帮助!