Custom Array of NSKeyedArchiver Objects

NOTE: Xcode 8 Beta 6

I'm not sure what I am missing, but for some reason I am getting the following error in the string NSKeyedArchiver.archivedData.

'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x60000024c690'
*** First throw call stack:

Here is my class that conforms to the NSCoding protocol:

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()
    }

}

And here is the code for archiving:

 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()

Any ideas?

+4
source share
1 answer

You cannot encode a Swift rename, e.g. PhraseType. Instead, give this enumeration a raw value and encode the raw value (and use it on decoding to restore the correct enumeration case).

When you do this, you need to throw your Swift array into NSArray to get it in the archive.

+6
source

Source: https://habr.com/ru/post/1652259/


All Articles