Objective-C. Property for C array

后端 未结 4 1095
不思量自难忘°
不思量自难忘° 2020-12-18 09:01

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 se

相关标签:
4条回答
  • 2020-12-18 09:07

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 09:16

    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;
    
    0 讨论(0)
  • 2020-12-18 09:28

    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.

    0 讨论(0)
  • 2020-12-18 09:28

    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.

    0 讨论(0)
提交回复
热议问题