用Swift 3编码

用Swift 3编码,swift,nscoding,Swift,Nscoding,我有下面的代码,我正试图把它放到Swift 3中。行super.encodeWithCoder(aCoder)出现问题。无论我做什么都会出错 import Foundation class ToDo: Task { var done: Bool @objc required init(coder aDecoder: NSCoder) { self.done = aDecoder.decodeObjectForKey("done") as! Bool super.init(cod

我有下面的代码,我正试图把它放到Swift 3中。行
super.encodeWithCoder(aCoder)
出现问题。无论我做什么都会出错

import Foundation
class ToDo: Task {
var done: Bool

@objc required init(coder aDecoder: NSCoder) {
    self.done = aDecoder.decodeObjectForKey("done") as! Bool
    super.init(coder: aDecoder)
}

@objc override func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(done, forKey: "done")
    super.encodeWithCoder(aCoder)
}

init(name: String, done: Bool) {
    self.done = done
    super.init(name: name)
}
}
我正在尝试转换成Swift 3

我有这个

import Foundation

class ToDo: Task {
var done: Bool

@objc required init(coder aDecoder: NSCoder) {
    self.done = aDecoder.decodeObject(forKey: "done") as! Bool
    super.init(coder: aDecoder)
}

@objc override func encode(with aCoder: NSCoder) {
    aCoder.encode(done, forKey: "done")
    // THis line gives an error
    super.encode(with aCoder)

}

init(name: String, done: Bool) {
    self.done = done
    super.init(name: name)
}

}
线路
super.encodeWithCoder(aCoder)
给出了一个错误。Swift没有给出提示,搜索也没有给出答案

根据评论进行编辑 原始代码“super.encodeWithCoder(aCoder)”给出了类型“Task”的错误值,但没有成员“encodeWithCoder”


super.encode(使用aCoder)给出预期的错误“;”separator

我认为应用程序崩溃的原因是您对Bool使用了
decodeObject()
函数

将代码更改为正确的函数将产生:

@objc required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.done = aDecoder.decodeBool(forKey: "done")
}

@objc override func encode(with aCoder: NSCoder) {
 aCoder.encode(done, forKey: "done")
}

错误是什么?虽然编码很奇怪,但这可能是因为我不熟悉重写它-我一直认为只有在IB中创建的视图才使用init(coder:)。这就是说,有两件事让我大吃一惊:(1)你没有公布你所犯错误的细节。(2) 我可能会看到生成错误,因为在调用super.ecode(with:coder)之前,您有一些代码。奖励:我刚才看到你的代码在那一行也缺少冒号。我非常确定这肯定不会生成。“行
super.encodeWithCoder(aCoder)
给出了一个错误”。在Swift 3示例中不存在该行。你是说你对
super.encode(使用aCoder)
的调用无法编译吗?正如dfd所指出的,这不会编译,因为它必须是
super.encode(with:aCoder)
。这是可行的,但我必须添加super.init(coder:aDecoder)以避免出现错误消息,我会相应地更新答案。未使用时未发生错误O:)