I need to create a mutable two-dimensional array in Objective-C.
For example I have:
NSMutableArray *sections;
NSMutableArray *rows;
<
Thanks to Jack for his code , i worked on it a bit; i need a multidimensional nsmutablearray for strings in one of my project , it still has some things that need to be fixed but works strings only at the moment , i will post it here , i am open for suggestions please cause i am only just a beginner in objective c at the moment...
@interface SectionArray : NSObject {
NSMutableArray *sections;
}
- initWithSections:(NSUInteger)intSections:(NSUInteger)intRow;
+ sectionArrayWithSections:(NSUInteger)intSections:(NSUInteger)intRows;
- objectInSection:(NSUInteger)intSection:(NSUInteger)intRow;
- (void)setObject:(NSString *)object:(NSUInteger)intSection:(NSUInteger)intRow;
@end
@implementation SectionArray
- initWithSections:(NSUInteger)intSections:(NSUInteger)intRow {
NSUInteger i;
NSUInteger j;
if ((self = [self init])) {
sections = [[NSMutableArray alloc] initWithCapacity:intSections];
for (i=0; i < intSections; i++) {
NSMutableArray *a = [NSMutableArray arrayWithCapacity:intRow];
for (j=0; j < intRow; j++) {
[a insertObject:[NSNull null] atIndex:j];
}
[sections addObject:a];
}
}
return self;
}
- (void)setObject:(NSString *)object:(NSUInteger)intSection:(NSUInteger)intRow {
[[sections objectAtIndex:intSection] replaceObjectAtIndex:intRow withObject:object];
}
- objectInSection:(NSUInteger)intSection:(NSUInteger)intRow {
return [[sections objectAtIndex:intSection] objectAtIndex:intRow];
}
+ sectionArrayWithSections:(NSUInteger)intSections:(NSUInteger)intRows {
return [[self alloc] initWithSections:intSections:intRows] ;
}
@end
This is working fine !!!
i am currently using it like this
SectionArray *secA = [[SectionArray alloc] initWithSections:2:2];
[secA setObject:@"Object":0:0];
[secA setObject:@"ObjectTwo":0:1];
[secA setObject:@"ObjectThree":1:0];
[secA setObject:@"ObjectFour":1:1];
NSString *str = [secA objectInSection:1:1];
NSLog(@" object is = %@" , str);
Thanks again Jack !!
This is what I did in order to initialize array of arrays.
NSMutableArray *arrayOfArrays = [[NSMutableArray alloc] initWithCapacity:CONST];
for (int i=0; i<=CONST; i++) {
[arrayOfArrays addObject:[NSMutableArray array]];
}
Then later in a code I could simply:
[[arrayOfArrays objectAtIndex:0] addObject:myObject];