将嵌套 类 写入 plist

write nested classes to plist

我有一对 类:ScaleWeightSetScale 包含一个 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()
}

您不能将自定义对象保存到 属性 列表中。 属性 列表只能包含类型的简短列表(字典、数组、字符串、数字(整数和浮点数)、日期、二进制数据和布尔值)。

看起来您正在将一组词典保存到您的 属性 列表中,而不是尝试直接保存您的自定义 类,这很好。

您应该创建一对方法来转换您的自定义 类 to/from 属性 列表对象。

让我们以您的 Scale 对象为例。

假设您创建了一个 toDict 方法将 Scale 对象转换为字典(如果需要,包含其他字典和数组)和一个 init(dict dict: Dictionary) 从字典创建一个新的 Scale 对象。

您可以使用 map 语句将 Scale 对象数组转换为字典数组,或将字典数组转换为 Scale 对象数组。