我有一对类:Scale
和 WeightSet
。 Scale
包含一个 WeightSet
数组:
class Scale {
var name: String
var factor: Double
var weights: [WeightSet] = []
...
}
class WeightSet {
var gauge: String
var initial: Double
var increment: Double
var lengthUnit: String
var weightUnit: String
...
}
有一个Scale
数组:
var scales = [Scale]()
我已经能够在 Xcode 中创建一个 plist,将其复制到文档目录并读入,但无法弄清楚如何将它写回 plist 并进行更改。我能找到的所有示例都是针对简单类的,我不知道如何处理 WeightSet
的嵌套数组。
仅供引用,这是我阅读它的方式:
func readScales() {
//read the plist file into input
let input = NSArray(contentsOfFile: path)
//loop through input
for i in 0..<input!.count {
//convert each element of input into a dictionary
let scaleDict = input![i] as! NSDictionary
//create a Scale object from the dictionary values
let scale = Scale(name: scaleDict.valueForKey("name") as! String, factor: scaleDict.valueForKey("factor") as! Double)
//convert the weights entry of the dictionary into an array of dictionaries
let weights = scaleDict.valueForKey("weights") as! [NSDictionary]
//loop through the array
for weight in weights {
//create a WeightSet object for each dictionary
let weightSet = WeightSet(gauge: weight.valueForKey("gauge") as! String, initial: weight.valueForKey("initial") as! Double, increment: weight.valueForKey("increment") as! Double, lengthUnit: weight.valueForKey("lengthUnit") as! String, weightUnit: weight.valueForKey("weightUnit") as! String)
//append the WeightSet object to the Scale Object
scale.weights.append(weightSet)
}
//append the Scale object to the scales array
scales.append(scale)
}
//print it to prove this worked!
printScales()
}
最佳答案
您不能将自定义对象保存到属性列表中。属性列表只能包含类型的简短列表(字典、数组、字符串、数字(整数和 float )、日期、二进制数据和 bool 值)。
看起来您正在将一组字典保存到您的属性列表中,而不是尝试直接保存您的自定义类,这很好。
您应该创建一对方法,将您的自定义类与属性列表对象相互转换。
让我们以您的 Scale 对象为例。
假设您创建了一个 toDict 方法,将 Scale 对象转换为字典(如果需要,包含其他字典和数组)和一个 init(dict dict: Dictionary) 从字典创建一个新的 Scale 对象。
您可以使用 map 语句将 Scale 对象数组转换为字典数组,或将字典数组转换为 Scale 对象数组。
关于ios - 将嵌套类写入 plist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35964054/