我试图将字典保存到UserDefaults然后我想获取数据或删除。
class userDefaultsManager {
static func getAllUsers()->[UserModel]{
if let all = UserDefaults.standard.array(forKey: "usersKey") as? [Dictionary<String,Any>] {
return all.map{UserModel.init(dictionary: $0)}
}
return []
}
static func insertUser(name:String, email:String)->Bool {
let newUserModel = UserModel.init(name: name, email: email)
var all = getAllUser()
all.append(newUserModel)
UserDefaults.standard.set(all.map{$0.dictionary}, forKey: "usersKey")
return UserDefaults.standard.synchronize()
}
static func deleteUser(email:String)->Bool {
var all = getAllUser()
let index = all.index{$0.email == email}
if index != nil {
all.remove(at: index!)
UserDefaults.standard.set(all.map{$0.dictionary}, forKey: "usersKey")
UserDefaults.standard.synchronize()
return true
} else {
return false
}
}
}
class UserModel:NSObject{
var name: String!
var email: String!
init(name:String, email:String) {
self. name = name
self. email = email
super.init()
}
init(dictionary:[String:Any]) {
self.name = ""
self.email = ""
super.init()
self.setValuesForKeys(dictionary)
}
var dictionary:[String:Any] {
return self.dictionaryWithValues(forKeys: ["name","email"]) //Error here
}
}
使用swift 3的代码,但我在var dictionary:[String:Any]
这是错误:
隐式Objective-C入口点 - [Myapp.UserModel name]是 已弃用,将在Swift 4中删除
请帮助解决此问题。
答案 0 :(得分:1)
你的类继承自NSObject,使用objc KVC,对于Swift3来说很好,因为Swift3默认将所有NSObject子类假设为@objc,在Swift4中你需要声明你的访问者@objc使它们可用于obj-c KVC运营。 https://forums.developer.apple.com/thread/81789