我有一系列银行卡,想要保存一次,以免多次从服务器下载数据。所以,问题在于我无法存档类的对象" Card"我宣布了。卡片类由四个字段组成,你可以看到,我相信这个问题的关键在于CardInfo结构,因为就我而言,结构不能符合NSCoding协议。我找到了一个将结构包装到类中的解决方案,但这些操作并没有帮助。
struct CardInfo
{
let type: CardType
let title: CardProducer
let number: String
let cvv: Int
}
extension CardInfo{
class Coding: NSObject, NSCoding{
let cardInfo: CardInfo!
init(cardInfo: CardInfo!){
self.cardInfo = cardInfo
super.init()
}
required init?(coder aDecoder:NSCoder) {
guard let type = CardType(rawValue: aDecoder.decodeObject(forKey: "type") as! Int), let title = CardProducer(rawValue:aDecoder.decodeObject(forKey: "title") as! Int), let number = aDecoder.decodeObject(forKey: "number") as? String, let cvv = aDecoder.decodeObject(forKey: "cvv") as? Int else { return nil }
cardInfo = CardInfo(type: type, title: title, number: number, cvv: cvv)
super.init()
}
func encode(with aCoder: NSCoder) {
guard let cardInfo = cardInfo else { return }
aCoder.encode(cardInfo.type.rawValue, forKey: "type")
aCoder.encode(cardInfo.title.rawValue, forKey: "title")
aCoder.encode(cardInfo.number, forKey: "number")
aCoder.encode(cardInfo.cvv, forKey: "cvv")
}
}
}
class Card: NSObject, NSCoding{
let id: Int
let title: String
let info: CardInfo
let balance: Int
init(id: Int, title: String, info: CardInfo, balance: Int) {
self.id = id
self.title = title
self.info = info
self.balance = balance
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.id, forKey: "id")
aCoder.encode(self.title, forKey: "title")
aCoder.encode(self.balance, forKey: "balance")
aCoder.encode(self.info, forKey: "info")
}
required init?(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeInteger(forKey: "id")
self.title = aDecoder.decodeObject(forKey: "title") as! String
self.info = aDecoder.decodeObject(forKey: "info") as! CardInfo
self.balance = aDecoder.decodeInteger(forKey: "balance")
}
}
编译器在这些行之后抛出错误。
UserDefaults.standard.saveObject(object:self.cards, key: "cards")
UserDefaults.standard.synchronize()
其中saveObject是我保存默认值的自定义方法,它适用于其他类的对象。