我创建了一个名为Player的模型。我需要将其保存在userdefault
中,并将每个用户附加到数组中,然后从NSuser
默认检索与用户有关的所有数据,以显示在表视图中。
我的问题是:如何存储此模型以及如何在nsuserdefault中将每个用户添加到数组中?
//this my model
class Player:NSObject {
var name = String()
var lastName = String()
var phone = Int()
var idCard = Int()
init( name: String, lastName: String, phone: Int, idCard :Int) {
//self.image = image
self.name = name
self.lastName = lastName
self.phone = phone
self.idCard = idCard
}
init(coder aDecoder :NSCoder!){
self.name = aDecoder.decodeObject(forKey: "name") as! String
self.lastName = aDecoder.decodeObject(forKey: "lastName") as! String
self.phone = aDecoder.decodeObject(forKey: "phone") as! Int
self.idCard = aDecoder.decodeObject(forKey: "idCard") as! Int
}
func intWithCoder(aDeCoder: NSCoder) -> Player {
self.name = aDeCoder.decodeObject(forKey: "name") as! String
self.lastName = aDeCoder.decodeObject(forKey: "lastName") as! String
self.phone = (aDeCoder.decodeObject(forKey: "phone") as? Int)!
self.idCard = (aDeCoder.decodeObject(forKey: "idCard") as? Int)!
return self
}
func encodeWithCoder(aCoder: NSCoder!){
aCoder.encode(name, forKey: "name")
aCoder.encode(lastName, forKey: "lastName")
aCoder.encode(phone, forKey: "phone")
aCoder.encode(idCard, forKey: "idCard")
}
}
// save model
@IBAction func save(_ sender: Any) {
var defaults: UserDefaults = UserDefaults.standard
defaults.set(item1Txt.text, forKey: "name")
defaults.set(item2Txt.text, forKey: "lastName")
defaults.set(item3Txt.text, forKey: "phone")
defaults.set(item4Txt.text, forKey: "idCard")
let player:[Player] = []
defaults.set(player, forKey: "player")
defaults.synchronize()
}