gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:53:53 25 4
gpt4 key购买 nike

我本来打算使用 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")

}

关于ios - 如何使用具有自定义类变量的 UserDefaults 对自定义类对象进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com