我试着保存自己的班级"解决方案"在pList中。它包含另一个类"解决方案"。
的数组let dict: NSMutableDictionary = ["XInitializerItem": Solution() ]
// saving values
dict.setObject(solutions, forKey: "best")
// writing back
dict.writeToFile(path, atomically: false)
但文件没有写。我认为这取决于课程。使用像String或Int这样的简单数据类型是有效的。缺少什么?
我添加了一些代码片段:
func savePlist( solutions : [Solution]) {
let path = getDocPath(plistfile + ".plist")
let dict: NSMutableDictionary = ["XInitializerItem": Solution() ]
// saving values
dict.setObject(solutions, forKey: "best")
// writing back
dict.writeToFile(path, atomically: false)
}
解决方案定义为:
class Solution : NSObject, NSCoding { // struct
let word : String
let score : Int
let priority : Int // needed for sorting criteria
let turn : Int // when was this reached?
let date : NSDate // same
let width : Int // which dimenions of the game?
let height : Int
var new : Bool // in this session (or loaded from best list)
init(word : String = "", score : Int = 0, bonus : Int = 0, turn : Int = 0, new : Bool = true) {
self.word = word
self.score = score
self.priority = score + bonus
self.turn = turn
self.date = NSDate()
self.width = NumColumns
self.height = NumRows
self.new = new
}
required init(coder aDecoder: NSCoder) {
word = aDecoder.decodeObjectForKey("word") as! String
score = aDecoder.decodeObjectForKey("score") as! Int
priority = aDecoder.decodeObjectForKey("priority") as! Int
turn = aDecoder.decodeObjectForKey("turn") as! Int
date = aDecoder.decodeObjectForKey("date") as! NSDate
width = aDecoder.decodeObjectForKey("width") as! Int
height = aDecoder.decodeObjectForKey("height") as! Int
new = false
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(word, forKey: "word")
aCoder.encodeObject(score, forKey: "score")
}
}
class Solutions : NSObject, NSCoding {
var solutions = [Solution]() // for high score etc...
override init() {
}
func bestSolution() -> Solution? {
if solutions.count == 0 { return nil }
var best = solutions[0]
for s in solutions {
if s.score > best.score {
best = s
}
}
return best
// return Solutions.reduce(0, { max($0.score, $1.score) })
}
func longestSolution() -> Solution? {
if solutions.count == 0 { return nil }
var best = solutions[0]
for s in solutions {
if s.word.characters.count > best.word.characters.count {
best = s
}
}
return best
// return Solutions.reduce(0, { max($0.score, $1.score) })
}
required init(coder aDecoder: NSCoder) {
solutions = aDecoder.decodeObjectForKey("solutions") as! [Solution]
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(solutions, forKey: "solutions")
}
}
答案 0 :(得分:1)
为了使用用户生成的类编写plist,该类需要支持NSCoding
协议。
来自Introduction to Property Lists:
但是如果对象符合NSCoding协议,则可以将它们存档为NSData对象,这些对象是与属性列表兼容的对象。