如何使用具有自定义类变量的UserDefaults对自定义类对象进行编码?

时间:2017-12-31 07:25:41

标签: ios swift encoding nsuserdefaults swift4

我打算使用Core Data,但认为这更容易,但无法在网上找到有关如何将 Cell 类数组存储为 Cell 班级本身。

class Cell: NSObject, NSCoding {
  var name:String!
  var tag:String?
  var more:String?
  var amount:String!
  var balance:String!
  var subCells:[Cell]?//THIS IS THE ONE I'M STUGGLING WITH

  override init() {
    super.init()
  }

  init(name: String, tag: String, more: String, amount: String, balance: String, subCells: [Cell] = [Cell]()) {
    super.init()
    self.name = name
    self.tag = tag
    self.more = more
    self.amount = amount
    self.balance = balance
    self.subCells = subCells//THIS
  }

  required init(coder decoder: NSCoder) {
    self.name = decoder.decodeObject(forKey: "name") as! String
    self.tag = decoder.decodeObject(forKey: "tag") as? String
    self.more = decoder.decodeObject(forKey: "more") as? String
    self.amount = decoder.decodeObject(forKey: "amount") as! String
    self.balance = decoder.decodeObject(forKey: "balance") as! String
    self.subCells = decoder.decodeObject(forKey: "subCells") as? [Cell]//THIS

  }

  func initWithCoder(decoder: NSCoder) -> Cell{
    self.name = decoder.decodeObject(forKey: "name") as! String
    self.tag = decoder.decodeObject(forKey: "tag") as? String
    self.more = decoder.decodeObject(forKey: "more") as? String
    self.amount = decoder.decodeObject(forKey: "amount") as! String
    self.balance = decoder.decodeObject(forKey: "balance") as! String
    self.subCells = decoder.decodeObject(forKey: "subCells") as? [Cell]//THIS
    return self
  }

  func encode(with aCoder: NSCoder) {      
    aCoder.encode(self.name, forKey: "name")
    aCoder.encode(self.tag, forKey: "tag")
    aCoder.encode(self.more, forKey: "more")
    aCoder.encode(self.amount, forKey: "amount")
    aCoder.encode(self.balance, forKey: "balance")
    aCoder.encode(self.subCells, forKey: "subCell")//THIS
  }  
}

我是否被迫使用核心数据来解决这个问题,或者我可以在对viewdidload()

中的整个类进行编码之前对数组进行编码

1 个答案:

答案 0 :(得分:0)

好吧我明白了

required init(coder decoder: NSCoder) {
    self.name = decoder.decodeObject(forKey: "name") as! String
    self.tag = decoder.decodeObject(forKey: "tag") as? String
    self.more = decoder.decodeObject(forKey: "more") as? String
    self.amount = decoder.decodeObject(forKey: "amount") as! String
    self.balance = decoder.decodeObject(forKey: "balance") as! String
    self.subCells = NSKeyedUnarchiver.unarchiveObject(with: (decoder.decodeObject(forKey: "subCells") as! NSData) as Data) as? [Cell]
}


func encode(with aCoder: NSCoder) {

    aCoder.encode(self.name, forKey: "name")
    aCoder.encode(self.tag, forKey: "tag")
    aCoder.encode(self.more, forKey: "more")
    aCoder.encode(self.amount, forKey: "amount")
    aCoder.encode(self.balance, forKey: "balance")
    aCoder.encode(NSKeyedArchiver.archivedData(withRootObject: self.subCells), forKey: "subCells")

}