NSCoder and custom types
Asked Answered
C

1

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;
Citrate answered 27/10, 2010 at 3:26 Comment(0)
R
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"];
}
Ronni answered 23/9, 2011 at 16:30 Comment(4)
Except that a change in the order internally in the enum would break the coding.Midkiff
And what class do you put these methods? They are types, not objects... NSKeyedArchiver?Foreclose
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.Ronni
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.Primate

© 2022 - 2024 — McMap. All rights reserved.