Objective-C. Property for C array

不羁的心 提交于 2019-11-29 07:46:34

You can do it if you wrap the array in a struct. Structs are supported in @property notation (see CGRect bounds on CALayer, for example).

First define your struct:

typedef struct {
    int contents[10][10];
} TenByTenMatrix;

Then, in your class interface, you can do:

@property (assign) TenByTenMatrix field;

Note that in this case, you can only get or set the whole array using the property. So you can't do

self.field.contents[0][0] = 1;

You'd have to do

TenByTenMatrix temp = self.field;
temp.contents[0][0] = 1;
self.field = temp;

If I understood you correctly, you need something like this:

@property(nonatomic, assign) int** field;

Note that you can't use retain here because it is only available for objects (and int is a primitive type).

Then you can use this in a following way:

    //some initialization - just an example, can be done in other way
self.field = malloc(10 *  sizeof(int));

for(int i = 0; i < 10; i++) {
    self.field[i] = malloc(10 * sizeof(int));
}

//actual usage
self.field[2][7] = 42;
int someNumber = self.field[2][7];

Because property's type is assign, you have to take care of memory management. You can create custom setter for field property and call free() in it.

Write setter and getter

- (int) field:(int)i j:(int)j {
    return field[i][j];
}

- (void)setField:(int)i j:(int)j toValue:(int)value {
    field[i][j] = value;
}

It s pretty simple.

    @interface MyClass
    {
        int _fields[10][10]; 
    }

    @property(readonly,nonatomic) int **fields;

    @end

    @implementation MyClass

    - (int *)fields
    {
        return _fields;
    }

    @end

Use readonly in property as it is a fixed pointer, which you wont be changing, which doesn't mean that you can't modify the values in the array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!