0

我有一堆银行卡,想保存一次,以免多次从服务器下载数据。所以,问题是我无法归档我声明的“卡片”类的对象。如您所见,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 是我保存默认值的自定义方法,它适用于其他类的对象。

4

0 回答 0