1

My custom object contains an array of unichar primitives. However there is no encodeUnichar:ForKey method in NSCoder. My solution is to transform my 2d unichar array into an NSString and then encode that.

However, the absence of a method to encode character makes me feel like I am missing something obvious, especially because I couldn't find the answer on Stack Overflow.

Before I embark on my NSString method, does anyone know if there is a simpler way to do this built in into the NSCoding protocol?

Thanks Lee.

Tangler
  • 168
  • 9

1 Answers1

1

A C array of fixed-size data is best encoded using encodeBytes:length:forKey:. See Encoding and Decoding C Data Types for full details.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • This will work great until you try to decode the value on a machine with a different endianess. I know, all Apple machine are little-endian but that may change in the future (it already has). – Nicolas Bachschmidt Jun 27 '12 at 17:58
  • You should swap the bytes before coding and after decoding with `NSSwapHostShortToLittle` and `NSSwapLittleShortToHost` or (`NSSwapHostShortToBig` and `NSSwapBigShortToHost` if you prefer big-endian). – Nicolas Bachschmidt Jun 27 '12 at 18:04
  • This works great as long as you remember that a unichar is 2 bytes long! – Tangler Jul 09 '12 at 12:01