Axeva
Axeva

Reputation: 4737

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!

Upvotes: 5

Views: 1157

Answers (2)

ughoavgfhw
ughoavgfhw

Reputation: 39905

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).

Upvotes: 7

indragie
indragie

Reputation: 18122

See the answer to this question. It details what you would need to do to convert the C array to an NSArray object.

Upvotes: 0

Related Questions