NSInvalidUnarchiveOperationException在Swift中解码存档中的对象时出错

NSInvalidUnarchiveOperationException在Swift中解码存档中的对象时出错,swift,cocoa-touch,foundation,Swift,Cocoa Touch,Foundation,请注意,我对Swift和iOS编程非常陌生,所以你们中的一些人可能会觉得这有点愚蠢 总之,我对Int对象进行编码,并将其与字符串关联,如下所示: func encodeWithCoder(aCoder: NSCoder) { // Note that `rating` is an Int aCoder.encodeObject(rating, forKey: PropertyKey.ratingKey) } 现在,当我尝试这样解码时: required convenience

请注意,我对Swift和iOS编程非常陌生,所以你们中的一些人可能会觉得这有点愚蠢

总之,我对
Int
对象进行编码,并将其与
字符串关联,如下所示:

func encodeWithCoder(aCoder: NSCoder) {
    // Note that `rating` is an Int
    aCoder.encodeObject(rating, forKey: PropertyKey.ratingKey)

}
现在,当我尝试这样解码时:

required convenience init?(coder aDecoder: NSCoder) {
    let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey)

    // Initialising a model class
    self.init(rating: rating)
}
常量
评级
应为
Int
,因为默认情况下
decodeIntegerWorky
应返回
Int

构建进行得很顺利,但当我运行它并记录一个错误时,它崩溃了,如下所示

Terminating app due to uncaught exception 
'NSInvalidUnarchiveOperationException', 
reason: '*** -[NSKeyedUnarchiver decodeInt64ForKey:]: 
value for key (rating) is not an integer number'
但是当我将
decodeIntegerWorky
更改为
decodeObjectForKey
并将返回值向下转换为
Int
时,它似乎工作得很好

像这样:

required convenience init?(coder aDecoder: NSCoder) {
    // Replaced `decodeInteger` with `decodeObject` and downcasting the return value to Int 
    let rating = aDecoder.decodeObjectForKey(PropertyKey.ratingKey) as! Int
    self.init(rating: rating)
}
我很难理解为什么会出现异常,因为我将其编码为
Int
,默认情况下
decodeInteger
返回Int

另外,我觉得
NSInvalidUnarchiveOperationException
告诉我,我使用了错误的操作来解码编码对象


这对我来说毫无意义,救命啊

这个问题已经解决了。感谢@PhillipMills的澄清

编码
Int
对象时,实现出错。我用
AnyObject
而不是
Int
对它进行编码,并试图将其解码为
Int
。这就是为什么我不得不贬低它,因为
Int
不起作用

编码应该这样做:

func encodeWithCoder(aCoder: NSCoder) {
    // Note that `rating` is an Int
    aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey)

}

我不确定斯威夫特的正确答案是什么,但是,当你说“我把它编码成Int”时,这并不完全准确。您使用的是
aCoder.encodeObject
而不是
Integer
版本。@PhillipMills嘿,非常感谢。我刚注意到。我应该使用
aCoder.encodeInteger
而不是
aCoder.encodeObject