如何使用具有自定义类变量的用户默认值对自定义类对象进行编码



我打算使用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(( 中对整个类进行编码之前对数组进行编码

好的,

我想通了

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")
}

最新更新