NSCoder: Encoding an enum?

Hi All,

I was wondering if there’s some special magic required to encode an enum…

I have a class that has a state which I store in a var called currentState. I’m trying to encode it but when I do I get a “unrecognized selector sent to instance” error. If I remove the state var, the class encodes and decodes fine.

Any suggestions?



enum state {
case created
case running
case paused
case completed

var currentState: state

aCoder.encode(currentState, forKey: “State”) // encoder

currentState = aDecoder.decodeObject(forKey: “State”) as! state // decoder

You could try having your state enum backed by a primitive, an Int for example. You will probably want to double check my information, but I believe NSCoder has the same restrictions on data types as UserDefaults.

Encoding would be saving the raw value. Decoding would involve getting the raw value, and then casting it as the appropriate state.

Could look something like this:

enum state: Int { case created = 0 case running case paused case completed } ... aCoder.encode(currentState.rawValue, forKey:"State") ... guard state = state(rawValue: aDecoder.decodeObject(forKey:"State")) else { //Handle error } currentState = state

ok, great, I’l give that a shot.