0

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:

https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/NumbersandValues/Articles/Values.html

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); 
Community
  • 1
  • 1
user2636834
  • 71
  • 2
  • 10
  • 1
    You need to debug the code. Use the debugger to view the values **at every step** through the code. Add NSLog() for values and find where things are going wrong. – zaph Sep 08 '14 at 01:50

1 Answers1

2

I just ran the code below and it all worked correctly, which makes me think the problem is elsewhere.

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* v_in = [NSValue valueWithBytes:&p_in objCType:@encode(Pixel)];

NSMutableArray* arr = [NSMutableArray array];
[arr addObject:v_in];

Pixel p_out = {3,3,3,3};
[[arr objectAtIndex:0] getValue:&p_out];
NSLog(@"Pixel out: %d %d %d %d",p_out.r,p_out.g,p_out.b, p_out.a);

My guess is that ledColors is nil when you try to fetch the object back out, which will do nothing, and leave you with uninitialised memory inside of p_out.

Tom Dalling
  • 23,305
  • 6
  • 62
  • 80
  • Thanks Tom, that was it. This code ran inside my awakeFromNib and I hadn't added ledColors = [[NSMutableArray alloc] init]; beforehand. – user2636834 Sep 08 '14 at 04:28