tags:

views:

262

answers:

1
+1  Q: 

Encoding C Structs

I have a struct defined like follows as part of an object. I'm trying to encode this for use with NSCoder with the aim of saving as well as Undo/Redo functionality.

struct myCol {
    float rd;
    float grn;
    float blu;
    float alp;
} toolColor;

So, there are methods to encode e.g. -encodeBool:, -encodeFloat:, -encodeObject: etc. But how do you do this for a struct?

+3  A: 

I think you should consider you struct myCol as memory buffer and encode it by something like encodeBytes function. Buffer length = size of your struct

macropas
You can either do it like this, as macropas says, or you can wrap it in an NSValue object.
Jason Coco
Thanks guys. Since an object is required I decided to use NSColor instead of struct. I guess I should have in the first place! But I'm learning.
Joe
Actually, wrapping a struct in a plain NSValue *doesn't* make it encodable. Just learned this the hard way. Details why are in the apple docs, "Archives and Serializations Programming Guide for Cocoa", "Encoding and Decoding C Data Types". I made my own category similar to NSValue(NSValueUIGeometryExtensions) and it works great; but I've not yet found a way to add one paralleling NSCoder(UIGeometryKeyedCoding) and have it be used, short of subclassing NSValue.
rgeorge