Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding a C style array of ints

I'm working on serializing a class that supports NSCoding. I've setup encodeWithCoder and initWithCoder, and all the standard Objective C data types work fine.

What I'm struggling with is how to encode a few simple C arrays. For example:

int bonusGrid[5];
int scoreGrid[10][10];
int solutionGrid[10][10];
int tileGrid[10][10];

Short of breaking them up and encoding each int one-by-one, I'm not sure how to deal with them. Is there a "standard" way to handle C arrays?

Thanks!

like image 520
Axeva Avatar asked Feb 12 '11 01:02

Axeva


1 Answers

One way would be to use NSData to wrap the arrays.

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:[NSData dataWithBytes:(void*)bonusGrid length:5*sizeof(int)] forKey:@"bonusGrid"];
    [coder encodeObject:[NSData dataWithBytes:(void*)scoreGrid length:10*10*sizeof(int)] forKey:@"scoreGrid"];
    ...
}

- (id)initWithCoder:(NSCoder *)coder
    if((self = [super initWithCoder:coder])) {
        NSData *data = [coder objectForKey:@"bonusGrid"];
        int *temporary = (int*)[data bytes];
        for(unsigned char i = 0; i < 5; ++i) bonusGrid[i] = temporary[i];
        data = [coder objectForKey:@"scoreGrid"];
        temporary = (int*)[data bytes];
        for(unsigned char i = 0; i < 10; ++i)
            for(unsigned char j = 0; j < 10; ++j)
                scoreGrid[i][j] = temporary[i*10 + j];
        ...
    }
    return self;
}

You could also use memcpy() to move the data back into your arrays, but it is not proper and not guaranteed to work on all systems (it does work on the iPhone and mac).

like image 84
ughoavgfhw Avatar answered Oct 05 '22 02:10

ughoavgfhw