注意:Xcode 8 Beta 6
我不确定我缺少什么,但由于某种原因,我在NSKeyedArchiver.archivedData行上收到以下错误。
'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x60000024c690'
*** First throw call stack:
这是我的类符合NSCoding协议:
enum PhraseType {
case create
case item
}
class Phrase: NSObject, NSCoding {
var englishPhrase :String!
var translatedPhrase :String!
var phraseType :PhraseType! = PhraseType.item
required init?(coder decoder: NSCoder) {
self.englishPhrase = decoder.decodeObject(forKey: "englishPhrase") as! String
self.translatedPhrase = decoder.decodeObject(forKey: "translatedPhrase") as! String
self.phraseType = decoder.decodeObject(forKey: "phraseType") as! PhraseType
}
func encode(with coder: NSCoder) {
coder.encode(self.englishPhrase, forKey: "englishPhrase")
coder.encode(self.translatedPhrase, forKey: "translatedPhrase")
coder.encode(self.phraseType, forKey: "phraseType")
}
init(englishPhrase :String, translatedPhrase :String) {
self.englishPhrase = englishPhrase
self.translatedPhrase = translatedPhrase
super.init()
}
}
以下是存档的代码:
let userDefaults = UserDefaults.standard
var phrases = userDefaults.object(forKey: "phrases") as? [Phrase]
if phrases == nil {
phrases = [Phrase]()
}
phrases?.append(phrase)
let phrasesData = NSKeyedArchiver.archivedData(withRootObject: phrases)
userDefaults.set(phrasesData, forKey: "phrases")
userDefaults.synchronize()
有什么想法吗?