我正在尝试使用NSCoding协议将数据读写到plist中。当我尝试写入[GolfHoles](这是NSObject的一个子类)时,会出现异常。我已经阅读了几篇不同方法的帖子,但都没有帮助。
class GolfCourse: NSObject, NSCoding {
var name: String = ""
var location: String = ""
var holes: [GolfHole] = [GolfHole]()
init(holes: [GolfHole]) {
self.holes = holes
}
// MARK: NSCoding Protocol
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(location, forKey: "location")
aCoder.encodeObject(holes, forKey: "holes") // exception here
}
required init(coder aDecoder: NSCoder) {
super.init()
name = aDecoder.decodeObjectForKey("name") as! String
location = aDecoder.decodeObjectForKey("location") as! String
holes = aDecoder.decodeObjectForKey("holes") as! [GolfHole]
}
override init() {
super.init()
for var i=0; i<18; i++ {
let newHole = GolfHole()
self.holes.append(newHole)
}
}
如何编写和读取数组?
GolfHole
类是否符合NSCoding
协议?它需要像你的GolfCourse
类一样实现这两个协议方法。 - rmaddy