I need something like this:
@property (nonatomic, retain) int field[10][10];
but this code doesn't work. How to replace it? I need both setter and getter methods
I need something like this:
@property (nonatomic, retain) int field[10][10];
but this code doesn't work. How to replace it? I need both setter and getter methods
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.