简体   繁体   中英

How to declare a C Array as a property of an Objective-C object?

我在将C数组声明为Objective-C属性时遇到麻烦(您知道@property和@synthesize,因此我可以使用点语法)...它只是3维int数组。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM