ios – Swift:不符合协议NSCoding

我正在尝试在 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")
    }

}

这是一个bug还是我只是想念一些东西?

解决方法

在报告导航器中的详细编译器消息中可以看到,
您的方法未正确声明:
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!) {

(这可能在beta版本之间发生变化)
此外,initWithCoder方法必须标记为必需:

required init(coder aDecoder: NSCoder) {   }

func encodeWithCoder(_aCoder: NSCoder) {   }

在Swift 3中,所需的方法

required init(coder aDecoder: NSCoder) {   }

func encode(with aCoder: NSCoder) {   }

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...