2016-01-12 20 views
1

請注意,我對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' 

似乎當我改變decodeIntegerForKeydecodeObjectForKey喪氣的返回值的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) 
} 

它讓我很難理解爲什麼例外,因爲我編碼它作爲一個IntdecodeInteger默認返回一個int。

此外,我覺得NSInvalidUnarchiveOperationException告訴我,我使用了錯誤的操作來解碼編碼的對象。

這對我沒有任何意義,幫助

+1

我不知道雨燕爲正確的答案是什麼,但是,當你說「我編碼它作爲一個詮釋」,即不完全準確。你使用'aCoder.encodeObject'而不是'Integer'版本。 –

+0

@PhillipMills嘿,非常感謝。我只是注意到了。我應該使用'aCoder.encodeInteger'而不是'aCoder.encodeObject' – metpb

回答

1

此問題已解決。感謝@PhillipMills澄清。

編碼Int對象時執行過程是錯誤的。我在AnyObject而不是Int中編碼它,並試圖將它解碼爲Int。這就是爲什麼我不得不貶低它,並解碼爲Int無法正常工作。

編碼應該完成的事情,像這樣:

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

} 
相關問題