【发布时间】:2015-12-09 03:06:07
【问题描述】:
我正在尝试使用 NSCoding 协议来读取和写入数据到 plist。当我尝试编写作为 NSObject 的子类的 [GolfHoles] 时出现异常。我已经阅读了几篇使用不同方法的帖子,但没有任何帮助。
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)
}
}
}
如何读写数组?
【问题讨论】:
-
无法决定是否投票关闭作为欺骗或不提供异常描述。无论哪种方式都结束了。
-
可能会因为不阅读 ios 标签 wiki 投票赞成关闭:-o ... 它说“请在发布与应用程序崩溃有关的任何问题之前阅读文章 My App crashed. Now what?,然后再发布有关应用程序崩溃的问题。它解释了如何正确调试 iOS 应用程序。当您没有正确的回溯和异常消息时,询问与崩溃有关的问题是没有意义的。”
-
您的
GolfHole类是否符合NSCoding协议?它需要像GolfCourse类那样实现这两个协议方法。 -
要查看导致错误的实际语句添加异常断点: 1. 从主菜单调试:断点:创建异常断点。 2. 右键单击断点并将异常设置为Objective-C。 3. 添加一个动作:“po $arg1”。运行应用程序以获取断点,您将位于导致异常的行,并且错误消息将在调试器控制台中。 Breakpoint example:
-
谢谢rmaddy。我未能使 GolfHole 类符合 NSCoding 协议。