This question has been asked a few times in SO, with the top two answers being:
What's the best way to put a c-struct in an NSArray?
How can I create an NSMutableArray of structs?
The Apple Documentation also shows this process:
The consensus seems to be to turn the struct into an object by way of NSValue. My problem when following this advice is that when I fetch back the data, I get bogus results.
My struct is very simple:
typedef struct { uint8_t r, g, b, a; } Pixel;
And as explained in the links above, I am able to add it to the array
NSMutableArray *ledColors;
By using NSValue in the following way:
Pixel p_in = {0,0,0,1};
NSLog(@"Pixel in: %d %d %d %d",p_in.r,p_in.g,p_in.b, p_in.a);
NSValue *p_obj = [NSValue valueWithBytes:&p_in objCType:@encode(Pixel)];
// NSValue *p_obj = [NSValue value:&p_in withObjCType:@encode(Pixel)]; //this seems to work too.
for (int i=0; i<numLeds; i++) {
[ledColors addObject:p_obj];
}
However, when I retrieve/fetch the data as described in the linked posts above, I do not get the original {0,0,0,1} but random integers instead:
Pixel p_out;
[[ledColors objectAtIndex:0] getValue:&p_out];
// Doesn't return the correct data
NSLog(@"Pixel out: %d %d %d %d",p_out.r,p_out.g,p_out.b, p_out.a);