我正在尝试在我用swift编写的类上使用NSCoding协议,但是当我实现所需的方法时,似乎无法弄清楚为什么编译器会抱怨它“不符合协议NSCoding”:
class ServerInfo: NSObject, NSCoding {
var username = ""
var password = ""
var domain = ""
var location = ""
var serverFQDN = ""
var serverID = ""
override init() {
}
init(coder aDecoder: NSCoder!) {
self.username = aDecoder.decodeObjectForKey("username") as NSString
self.password = aDecoder.decodeObjectForKey("password") as NSString
self.domain = aDecoder.decodeObjectForKey("domain") as NSString
self.location = aDecoder.decodeObjectForKey("location") as NSString
self.serverFQDN = aDecoder.decodeObjectForKey("serverFQDN") as NSString
self.serverID = aDecoder.decodeObjectForKey("serverID") as NSString
}
func encodeWithCoder(_aCoder: NSCoder!) {
_aCoder.encodeObject(self.username, forKey: "username")
_aCoder.encodeObject(self.password, forKey: "password")
_aCoder.encodeObject(self.domain, forKey: "domain")
_aCoder.encodeObject(self.location, forKey: "location")
_aCoder.encodeObject(self.serverFQDN, forKey: "serverFQDN")
_aCoder.encodeObject(self.serverID, forKey: "serverID")
}
}
这是一个错误还是我错过了什么?
答案 0 :(得分:19)
正如您在报告导航器中的详细编译器消息中所看到的, 您的方法未正确声明:
error: type 'ServerInfo' does not conform to protocol 'NSCoding' class ServerInfo: NSObject, NSCoding { ^ Foundation.NSCoding:2:32: note: protocol requires function 'encodeWithCoder' with type '(NSCoder) -> Void' @objc(encodeWithCoder:) func encodeWithCoder(aCoder: NSCoder) ^ note: candidate has non-matching type '(NSCoder!) -> ()' func encodeWithCoder(_aCoder: NSCoder!) { ^ Foundation.NSCoding:3:25: note: protocol requires initializer 'init(coder:)' with type '(coder: NSCoder)' @objc(initWithCoder:) init(coder aDecoder: NSCoder) ^ note: candidate has non-matching type '(coder: NSCoder!)' init(coder aDecoder: NSCoder!) {
(这可能在测试版发布之间发生了变化。)
此外,initWithCoder
方法必须标记为required
:
required init(coder aDecoder: NSCoder) { }
func encodeWithCoder(_aCoder: NSCoder) { }
在 Swift 3 中,所需的方法是
required init(coder aDecoder: NSCoder) { }
func encode(with aCoder: NSCoder) { }
答案 1 :(得分:4)
参数不会被隐式展开(删除!),初始化程序需要required
修饰符:
required init(coder aDecoder: NSCoder) {
...
func encodeWithCoder(_aCoder: NSCoder) {
适用于Swift 3
已经承诺了一个小但重要的变化。 init方法相同,但encodeWithCoder方法已被修改。
required init(coder aDecoder: NSCoder) {
...
}
func encode(with _aCoder: NSCoder) {
...
}
答案 2 :(得分:0)
对于Swift 3(在Xcode 8.2 beta(8C23)上)
它似乎又改变了。这是我可以开始工作的唯一变体......
func encodeWithCoder(_ _aCoder: NSCoder) {
...
}