請注意,我對Swift和iOS編程非常陌生,所以你們中的一些人可能會覺得這有點愚蠢。從Swift中的檔案解碼對象時出現NSInvalidUnarchiveOperationException錯誤
無論如何,所以我編碼Int
對象,並將其與String
鍵像這樣關聯:
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)
}
的常數rating
預計爲Int
,因爲decodeIntegerForKey
預計會返回默認Int
構建順利,但是當我運行它時崩潰並記錄下面重復的錯誤。
Terminating app due to uncaught exception
'NSInvalidUnarchiveOperationException',
reason: '*** -[NSKeyedUnarchiver decodeInt64ForKey:]:
value for key (rating) is not an integer number'
但似乎當我改變decodeIntegerForKey
到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
告訴我,我使用了錯誤的操作來解碼編碼的對象。
這對我沒有任何意義,幫助
我不知道雨燕爲正確的答案是什麼,但是,當你說「我編碼它作爲一個詮釋」,即不完全準確。你使用'aCoder.encodeObject'而不是'Integer'版本。 –
@PhillipMills嘿,非常感謝。我只是注意到了。我應該使用'aCoder.encodeInteger'而不是'aCoder.encodeObject' – metpb