Creating a two dimensional array in Objective-C

后端 未结 6 518
Happy的楠姐
Happy的楠姐 2020-12-01 09:46

Whats the easiest way to declare a two dimensional array in Objective-C? I am reading an matrix of numbers from a text file from a website and want to take the data and pla

6条回答
  •  感动是毒
    2020-12-01 09:58

    I'm not absolutely certain what you are looking for, but my approach to a two dimensional array would be to create a new class to encapsulate it. NB the below was typed directly into the StackOverflow answer box so it is not compiled or tested.

    @interface TwoDArray : NSObject
    {
    @private
        NSArray* backingStore;
        size_t numRows;
        size_t numCols;
    }
    
    // values is a linear array in row major order
    -(id) initWithRows: (size_t) rows cols: (size_t) cols values: (NSArray*) values;
    -(id) objectAtRow: (size_t) row col: (size_t) col;
    
    @end
    
    @implementation TwoDArray
    
    
    -(id) initWithRows: (size_t) rows cols: (size_t) cols values: (NSArray*) values
    {
        self = [super init];
        if (self != nil)
        {
            if (rows * cols != [values length])
            {
                // the values are not the right size for the array
                [self release];
                return nil;
            }
            numRows = rows;
            numCols = cols;
            backingStore = [values copy];
        }
        return self;
    }
    
    -(void) dealloc
    {
        [backingStore release];
        [super dealloc];
    }
    
    -(id) objectAtRow: (size_t) row col: (size_t) col
    {
        if (col >= numCols)
        {
            // raise same exception as index out of bounds on NSArray.  
            // Don't need to check the row because if it's too big the 
            // retrieval from the backing store will throw an exception.
        }
        size_t index = row * numCols + col;
        return [backingStore objectAtIndex: index];
    }
    
    @end
    

提交回复
热议问题