I need to create a mutable two-dimensional array in Objective-C.
For example I have:
NSMutableArray *sections;
NSMutableArray *rows;
<
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