我有一个包含我已创建的对象的数组。我希望管理器类从磁盘加载这个数组,以便我可以继续追加到数组。
---这就是我想要管理阵列的类别
class FoodManager{
var foodList : [FoodItem]
func addFood(name : String, carbs : Int, fat: Int, protein : Int) {
let food = FoodItem(name: name, carbs: carbs, protein: protein, fat: fat)
foodList.append(food)
}
init(){
foodList = [FoodItem]()
//Here is where I would like to load the array to initialize foodList or if the file doesn't exist, create a new array
}
}
-----这是阵列中的一类----
class FoodItem{
let name: String
let carbs: Int
let protein: Int
let fat: Int
init(name: String, carbs: Int, protein: Int, fat: Int){
self.name = name
self.carbs = carbs
self.protein = protein
self.fat = fat
}
}
我发现了很多关于保存一个只有原始数据类型的类的信息,但是找不到需要保存用户定义对象数组的例子。
谢谢!
答案 0 :(得分:0)
如果要保存以供重复使用,这将是您的自定义类的实现。
class FoodItem: NSCoding {
let name: String?
let carbs: Int?
let protein: Int?
let fat: Int?
required init(name: String, carbs: Int, protein: Int, fat: Int){
self.name = name
self.carbs = carbs
self.protein = protein
self.fat = fat
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(carbs, forKey: "carbs")
aCoder.encode(protein, forKey: "protein")
aCoder.encode(fat, forKey: "fat")
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey : "name") as? String
self.carbs = aDecoder.decodeObject(forKey : "carbs") as? Int
self.protein = aDecoder.decodeObject(forKey : "protein") as? Int
self.fat = aDecoder.decodeObject(forKey : "fat") as? Int
}
}
要将此类对象保存到userdefaults,您可以使用:
let userDefaults = UserDefaults.standard
let encodedData = NSKeyedArchiver.archivedData(withRootObject: YourObjectToSave)
userDefaults.set(encodedData, forKey: "DummyName")
userDefaults.synchronize()
要从userdefaults获取对象,您可以使用:
let decoded = UserDefaults.standard.object(forKey: "DummyName") as! NSData
let decodedClassObject = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as! FoodItem
假设我有一系列FoodItems:
let itemArray: [FoodItem] = [item1, item2, item3]
您现在可以使用相同的代码来保存此数组:
let userDefaults = UserDefaults.standard
let encodedData = NSKeyedArchiver.archivedData(withRootObject: YourObjectToSave)
userDefaults.set(encodedData, forKey: "itemArray")
userDefaults.synchronize()
现在将数组检索为:
let decoded = UserDefaults.standard.object(forKey: "itemArray") as! NSData
let decodedClassObject = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as! [FoodItem]
答案 1 :(得分:-1)
您需要使用NSCoder类在您的经理类中保存自定义对象数组。