Objective-C. Property for array C

I need something like this:

@property (nonatomic, retain) int field[10][10]; 

but this code does not work. How to replace it? I need setter and getter methods

+4
source share
4 answers

You can do this if you wrap the array in a structure. Structures are supported in @property notation (see, for example, CGRect ratings on CALayer).

First define your structure:

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

Then in your class interface you can:

 @property (assign) TenByTenMatrix field; 

Note that in this case you can get or set the whole array using the property. Therefore you cannot do

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

You will need to do

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

If you understand correctly, you need something like this:

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

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

Then you can use it as follows:

  //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]; 

Since the type of the property is assign , you need to take care of memory management. You can create your own typesetter for the field property and call free() on it.

+3
source

Write setter and getter

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

It is pretty simple.

  @interface MyClass { int _fields[10][10]; } @property(readonly,nonatomic) int **fields; @end @implementation MyClass - (int *)fields { return _fields; } @end 

Use readonly in the property, since it is a fixed pointer that you will not change, which does not mean that you cannot change the values ​​in the array.

0
source

Source: https://habr.com/ru/post/1490480/


All Articles