7

How do you use NSCoder to encode and decode custom types?

For example, how would you use NSCoder with an instance of "STATE" where:

typedef enum { ON, OFF } STATE;
Ken
  • 30,811
  • 34
  • 116
  • 155

1 Answers1

13

You can treat them as integers as they are implicitly assigned integer values:

- (void) encodeWithCoder: (NSCoder *)coder {
  ...
  [coder encodeInt:type forKey:@"state"];
}

- (id) initWithCoder: (NSCoder *)coder {
  ...
  state = [coder decodeIntForKey:@"state"];
}
Ushox
  • 768
  • 6
  • 13
  • 1
    Except that a change in the order internally in the enum would break the coding. – Kenneth Jun 29 '12 at 08:39
  • And what class do you put these methods? They are types, not objects... `NSKeyedArchiver`? – Alex Gray Nov 23 '12 at 01:32
  • To support encoding and decoding of instances, a class must adopt the NSCoding protocol and implement its methods. An object being encoded or decoded is responsible for encoding and decoding its state. – Ushox Nov 30 '12 at 06:01
  • You can encode an additional "objectVersion" identifier to account for differences that may occur in enum order as the object architecture evolves. An enum is also signed, so you can squeeze in negative values which may help in some circumstances. – ctpenrose Jan 04 '13 at 01:19