Swift:不符合协议NSCoding

编程入门 行业动态 更新时间:2024-10-14 06:17:24
本文介绍了Swift:不符合协议NSCoding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在我用swift编写的类上使用NSCoding协议,但似乎无法弄清楚为什么编译器在我实现所需方法时抱怨它不符合协议NSCoding:

I am trying to use the NSCoding protocol on a class I have written in swift, but cannot seem to figure out why the compiler complains that it "does not conform to protocol NSCoding" when I do implement the required methods:

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") } }

这是一个错误还是我错过了什么?

Is this a bug or am I just missing something?

推荐答案

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

As you can see in the detailed compiler messages in the Report navigator, your methods are not declared correctly:

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 :

(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) { }

更多推荐

Swift:不符合协议NSCoding

本文发布于:2023-11-26 08:43:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633418.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不符合   协议   Swift   NSCoding

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!