我有两个类: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,将它复制到documents目录中并将其读取,但是我想不出如何通过更改将它写回plist。我能找到的所有示例都是针对简单类的,我不知道如何处理WeightSet
的嵌套数组。
FYI,以下是我在以下文章中的阅读方式:
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()
}
发布于 2016-03-12 22:42:34
不能将自定义对象保存到属性列表中。属性列表只能包含简短的类型列表(字典、数组、字符串、数字(整数和浮点数)、日期、二进制数据和布尔值)。
看起来,您正在将一组字典保存到属性列表中,而不是试图直接保存自定义类,这很好。
您应该创建一对将自定义类转换为/从属性列表对象的方法。
让我们以您的缩放对象为例。
假设您创建了一个toDict方法,该方法将一个缩放对象转换为一个字典(如果需要的话包含其他字典和数组),并创建一个init( dict :字典),从一个字典中创建一个新的刻度对象。
您可以使用map语句将缩放对象数组转换为字典数组,或者将字典数组转换为缩放对象数组。
https://stackoverflow.com/questions/35964054
复制相似问题