在自定义类上使用NSCoding时在self.init调用错误之前使用的'self' [英] 'self' used before self.init call error while using NSCoding on a custom class
本文介绍了在自定义类上使用NSCoding时在self.init调用错误之前使用的'self'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编码自定义类,因此可以使用NSKeyedArchiver.archivedDataWithRootObject
I'm trying to encode a custom class so I can save it using NSKeyedArchiver.archivedDataWithRootObject
但是当我尝试遵循NSCoding协议时,出现此错误:self.init之前使用了'self'.这是我的代码:
but when I try to conform to the NSCoding protocol, I get this error : 'self' used before self.init. Here is my code:
class MemberRewardsInfo: NSObject, NSCoding {
var id: Int?
required convenience init?(coder aDecoder: NSCoder) {
guard let unarchivedId = aDecoder.decodeObjectForKey("id") as? Int
else {
return nil
}
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(id, forKey: "id")
}
}
这很烦人,不确定为什么它不起作用.
its pretty annoying, not sure why it's not working.
推荐答案
该错误消息具有误导性,但是您需要将init(coder:)
设置为指定的初始化程序.
The error message is sort of misleading, but you need to make init(coder:)
a designated initializer.
您需要将init(code:)
修改为以下内容:
You need to modify your init(code:)
to something like this:
required init?(coder aDecoder: NSCoder) {
guard let unarchivedId = aDecoder.decodeObjectForKey("id") as? Int else {
return nil
}
self.id = unarchivedId
super.init()
}
这篇关于在自定义类上使用NSCoding时在self.init调用错误之前使用的'self'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文