in iOS 6 you can use subscript to define a matrix class that uses the square bracket syntax matrix[row][col]
where you can store objects and they are correctly retained by the matrix, differently than using a C array
First create a Row object, defined like this
- (id)initWithElementNumber:(NSUInteger)num {
if (self = [super init]) {
_row = [NSMutableArray arrayWithCapacity:num];
for (int j = 0; j < num; j++)
[_row addObject:[NSNull null]];
}
return self;
}
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
return self.row[idx];
}
- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)idx {
self.row[idx] = object;
}
@end
And then a Matrix class that uses the Row class previously defined:
@implementation UKMatrix
- (id)initWithRows:(NSUInteger)numRows columsn:(NSUInteger)numCol {
if (self = [super init])
{
_numCol = numCol;
_numRows = numRows;
_rows = [NSMutableArray arrayWithCapacity:numRows];
for (int j = 0; j < numRows; j++)
[_rows addObject:[[UKRow alloc] initWithElementNumber:numCol]];
}
return self;
}
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
return self.rows[idx];
}
- (NSString *)description {
NSString *matrixDesc = @"";
for (int j = 0; j < self.numRows; j++) {
matrixDesc = [matrixDesc stringByAppendingString:@"\n"];
for (int k = 0; k < self.numCol; k++)
matrixDesc = [matrixDesc stringByAppendingFormat:@" %@ ",self[j][k]];
}
return matrixDesc;
}
@end
then you can use the Matrix with the following syntax
UKMatrix *matrix = [[UKMatrix alloc] initWithRows:4 columsn:2];
matrix[1][1] = @2;
NSLog(@"%@", matrix);