2D arrays using NSMutableArray

后端 未结 8 830
夕颜
夕颜 2020-11-29 21:41

I need to create a mutable two-dimensional array in Objective-C.

For example I have:

NSMutableArray *sections;
NSMutableArray *rows;
<
8条回答
  •  独厮守ぢ
    2020-11-29 22:10

    Reviving an old thread, but I reworked Jack's code so 1. it compiles and 2. it is in the order of 2D c arrays [rows][columns] instead of [sections(columns)][rows] as he has it. Here you go!

    TwoDArray.h:

    #import 
    
    @interface TwoDArray : NSObject
    
    @property NSMutableArray *rows;
    
    - initWithRows:(NSUInteger)rows columns:(NSUInteger)columns;
    + sectionArrayWithRows:(NSUInteger)rows columns:(NSUInteger)columns;
    - objectInRow:(NSUInteger)row column:(NSUInteger)column;
    - (void)setObject:(id)obj inRow:(NSUInteger)row column:(NSUInteger)column;
    
    @end
    

    TwoDArray.m:

    #import "TwoDArray.h"
    
    @implementation TwoDArray
    
    - (id)initWithRows:(NSUInteger)rows columns:(NSUInteger)columns {
        if ((self = [self init])) {
            self.rows = [[NSMutableArray alloc] initWithCapacity: rows];
            for (int i = 0; i < rows; i++) {
                NSMutableArray *column = [NSMutableArray arrayWithCapacity:columns];
                for (int j = 0; j < columns; j++) {
                    [column setObject:[NSNull null] atIndexedSubscript:j];
                }
                [self.rows addObject:column];
            }
        }
        return self;
    }
    + (id)sectionArrayWithRows:(NSUInteger)rows columns:(NSUInteger)columns {
        return [[self alloc] initWithRows:rows columns:columns];
    }
    - (id)objectInRow:(NSUInteger)row column:(NSUInteger)column {
        return [[self.rows objectAtIndex:row] objectAtIndex:column];
    }
    - (void)setObject:(id)obj inRow:(NSUInteger)row column:(NSUInteger)column {
        [[self.rows objectAtIndex:row] replaceObjectAtIndex:column withObject:obj];
    }
    @end
    

提交回复
热议问题