首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将嵌套类写入plist

将嵌套类写入plist
EN

Stack Overflow用户
提问于 2016-03-12 22:24:00
回答 1查看 406关注 0票数 1

我有两个类:ScaleWeightSetScale中包含一个WeightSet数组:

代码语言:javascript
运行
复制
class Scale {
    var name: String
    var factor: Double
    var weights: [WeightSet] = []

    ...

 }
代码语言:javascript
运行
复制
class WeightSet {
    var gauge: String
    var initial: Double
    var increment: Double
    var lengthUnit: String
    var weightUnit: String

   ...

}

有一个Scale数组

代码语言:javascript
运行
复制
var scales = [Scale]()

我已经能够在Xcode中创建一个plist,将它复制到documents目录中并将其读取,但是我想不出如何通过更改将它写回plist。我能找到的所有示例都是针对简单类的,我不知道如何处理WeightSet的嵌套数组。

FYI,以下是我在以下文章中的阅读方式:

代码语言:javascript
运行
复制
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()
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-12 22:42:34

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

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

您应该创建一对将自定义类转换为/从属性列表对象的方法。

让我们以您的缩放对象为例。

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35964054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档