gpt4 book ai didi

ios - Swift:不符合协议(protocol) NSCoding

转载 作者:IT王子 更新时间:2023-10-29 05:29:25 25 4
gpt4 key购买 nike

我正在尝试在我用 swift 编写的类上使用 NSCoding 协议(protocol),但似乎无法弄清楚为什么编译器在我实现所需方法时提示它“不符合协议(protocol) 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")
}

}

这是一个错误还是我只是遗漏了什么?

最佳答案

正如您在报告导航器中的详细编译器消息中所见,您的方法未正确声明:

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!) {

(This may have changed between the beta releases.)In addition, the initWithCoder method has to be marked as required:

required init(coder aDecoder: NSCoder) {   }

func encodeWithCoder(_aCoder: NSCoder) { }

Swift 3 中,所需的方法是

required init(coder aDecoder: NSCoder) {   }

func encode(with aCoder: NSCoder) { }

关于ios - Swift:不符合协议(protocol) NSCoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25750088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com