Objective C - Create a multi-dimensional array with the dimensions specified at initialisation

前端 未结 3 795
北恋
北恋 2020-12-19 15:57

I am trying to create a class where the width and height of a 2 dimensional array can be dynamically created at the point of initialisation with init parameters.

I h

3条回答
  •  粉色の甜心
    2020-12-19 16:21

    Here's another way. Of course this is just for int but the code could easily be altered for other datatypes.

    AOMatrix.h:

    #import 
    
    
    @interface AOMatrix : NSObject {
    
    @private
        int* matrix_;
        uint columnCount_;
        uint rowCount_;
    }
    
    - (id)initWithRows:(uint)rowCount Columns:(uint)columnCount;
    
    - (uint)rowCount;
    - (uint)columnCount;
    
    - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex;
    - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex;
    
    @end
    

    AOMatrix.m

    #import "AOMatrix.h"
    
    #define INITIAL_MATRIX_VALUE 0
    #define DEFAULT_ROW_COUNT 4
    #define DEFAULT_COLUMN_COUNT 4
    
    /****************************************************************************
     * BIG NOTE:
     * Access values in the matrix_ by matrix_[rowIndex*columnCount+columnIndex]
     ****************************************************************************/
    @implementation AOMatrix
    
    - (id)init {
        return [self initWithRows:DEFAULT_ROW_COUNT Columns:DEFAULT_COLUMN_COUNT];
    }
    
    - (id)initWithRows:(uint)initRowCount Columns:(uint)initColumnCount {
        self = [super init];
        if(self) {
            rowCount_ = initRowCount;
            columnCount_ = initColumnCount;
            matrix_ = malloc(sizeof(int)*rowCount_*columnCount_);
    
            uint i;
            for(i = 0; i < rowCount_*columnCount_; ++i) {
                matrix_[i] = INITIAL_MATRIX_VALUE;
            }
    //      NSLog(@"matrix_ is %ux%u", rowCount_, columnCount_);
    //      NSLog(@"matrix_[0] is at %p", &(matrix_[0]));
    //      NSLog(@"matrix_[%u] is at %p", i-1, &(matrix_[i-1]));
        }
        return self;
    }
    
    - (void)dealloc {
        free(matrix_);
        [super dealloc];
    }
    
    - (uint)rowCount {
        return rowCount_;
    }
    
    - (uint)columnCount {
        return columnCount_;
    }
    
    - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex {
    //  NSLog(@"matrix_[%u](%u,%u) is at %p with value %d", rowIndex*columnCount_+columnIndex, rowIndex, columnIndex, &(matrix_[rowIndex*columnCount_+columnIndex]), matrix_[rowIndex*columnCount+columnIndex]);
        return matrix_[rowIndex*columnCount_+columnIndex];
    }
    - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex {
        matrix_[rowIndex*columnCount_+columnIndex] = value;
    }
    
    @end
    

提交回复
热议问题