NSInvalidUnarchiveOperationException在Swift中解码存档中的对象时出错
请注意,我对Swift和iOS编程非常陌生,所以你们中的一些人可能会觉得这有点愚蠢 总之,我对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
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