我试图在我快速编写的类上使用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") } }
这是一个错误还是我只是缺少一些东西?
如您在报告导航器中详细的编译器消息中所见,您的方法未正确声明:
错误:类型“ ServerInfo”不符合协议“ NSCoding” ServerInfo类:NSObject,NSCoding { ^ Foundation.NSCoding:2:32:注意:协议要求函数'encodeWithCoder'类型为((NSCoder)-> Void' @objc(encodeWithCoder :) func encodeWithCoder(aCoder:NSCoder) ^ 注意:候选者的类型不匹配'(NSCoder!)->()' func encodeWithCoder(_aCoder:NSCoder!){ ^ Foundation.NSCoding:3:25:注意:协议要求初始化类型为'(coder:NSCoder)'的初始化程序'init(coder :)' @objc(initWithCoder :) init(编码器aDecoder:NSCoder) ^ 注意:候选人具有不匹配的类型'(coder:NSCoder!)' init(coder aDecoder:NSCoder!){
(在beta版本之间可能有所变化。)此外,该initWithCoder方法必须标记为required:
initWithCoder
required
required init(coder aDecoder: NSCoder) { } func encodeWithCoder(_aCoder: NSCoder) { }
在 Swift 3中 ,所需的方法是
required init(coder aDecoder: NSCoder) { } func encode(with aCoder: NSCoder) { }