I am attempting to add a category to NSMutableArray
to allow me to use it as a 2D array (backed by the 1D array, with a method to convert x & y indexes into a flat index). As I am not allowed to add instance variables to a category, how should I keep track of row and column counts which are required to calculate the index into the array?
Here is the interface:
@interface NSMutableArray (TK2DMutableArray)
- (id) initWithColumns:(int) columns rows:(int) rows;
- (id) objectAtColumn:(int) col row:(int) row;
- (void) putObject:(id) object atColumn:(int) x Row:(int) y;
@end
And here is the implementation:
@implementation TK2DMutableArray
- (id) initWithColumns:(int) x rows:(int) y {
self = [self initWithCapacity:x * y];
return self;
}
- (id) objectAtColumn:(int) col row:(int) row {
return [self objectAtIndex:[self indexAtColumn:col row:row]];
}
- (void) putObject:(id) object atColumn:(int) x row:(int) y {
[self replaceObjectAtIndex:[self indexAtColumn:x row:y] withObject:object];
}
- (int) indexAtColumn:(int) col row:(int) row {
return (col + (row * rows));
}
@end
I originally coded it up as a subclass of NSMutableArray
; I now know that was a mistake having read up a little on class clusters. The problem is right there in the last method - what should I do with rows
? It'd be a regular old ivar if I was subclassing.
I'm fully expecting to be told to create a new class with an NSMutableArray
as a property, but I wanted to see if there was a way to do it with categories first.
Many thanks.