4

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

Greg
  • 9,068
  • 6
  • 49
  • 91
Gargo
  • 1,135
  • 1
  • 10
  • 21
  • Refer this post: http://stackoverflow.com/questions/476843/create-an-array-of-integers-property-in-objective-c – NightFury Jul 09 '13 at 12:52
  • Also, why can't you simply use an NSArray? – Michał Ciuba Jul 09 '13 at 13:14
  • 1)You advice convert to NSArray and convert from. You also need to convert simple variables of int type to something like NSValue objects. Or I need to rewrite all the previous code to use an NSArray instead of c arrays. 2)I use a multiple c arrays of int instead of one NSArray of objects with parameters because the variables are enough simple and these arrays represent something like logic layers – Gargo Jul 09 '13 at 14:03

4 Answers4

6

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;
joerick
  • 16,078
  • 4
  • 53
  • 57
4

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.

Michał Ciuba
  • 7,876
  • 2
  • 33
  • 59
0

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;
}
Parag Bafna
  • 22,812
  • 8
  • 71
  • 144
0

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.

Amogh Talpallikar
  • 12,084
  • 13
  • 79
  • 135