views:

195

answers:

1

I'm having trouble declaring a C Array as an Objective-C Property (You know @property, and @synthesize so I can use dot syntax)...Its just a 3 dimensional int array..

+5  A: 

You can't -- arrays are not lvalues in C. You'll have to declare a pointer property instead and rely on code using the correct arraybounds, or instead use an NSArray property.

Example:

@interface SomeClass
{
    int width, height, depth;
    int ***array;
}

- (void) initWithWidth:(int)width withHeight:(int)height withDepth:(int)depth;
- (void) dealloc;

@property(nonatomic, readonly) array;
@end

@implementation SomeClass

@synthesize array;

 - (void) initWithWidth:(int)width withHeight:(int)height withDepth:(int)depth
{
    self->width  = width;
    self->height = height;
    self->depth  = depth;
    array = malloc(width * sizeof(int **));
    for(int i = 0; i < width; i++)
    {
        array[i] = malloc(height * sizeof(int *));
        for(int j = 0; j < height; j++)
            array[i][j] = malloc(depth * sizeof(int));
    }
}

- (void) dealloc
{
    for(int i = 0; i < width; i++)
    {
        for(int j = 0; j < height; j++)
            free(array[i][j]);
        free(array[i]);
    }
    free(array);
}

@end

Then you can use the array property as a 3-dimensional array.

Adam Rosenfield
Correct, but I find it simpler to use a single allocation and then some simple math to access the elements within the array as if it were multi-dimensional. This tends to be more efficient in terms of memory use (assuming you don't go sparse).
bbum