我正在尝试向NSMutableArray
添加一个类别,以允许我将它用作二维数组(由1D数组支持,并将方法将x索引转换为平面索引)。由于我不允许将实例变量添加到类别中,因此我应该如何跟踪计算数组中索引所需的行数和列数?类别和实例变量
这里的接口:
@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
这里是实现:
@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
我最初的代码它作为NSMutableArray
一个子类;我现在知道,在集群上阅读了一些内容是一个错误。问题是在最后一个方法 - 我应该怎么做rows
?如果我是继承人,那会是一个普通的老伊娃。
我完全期待被告知创建一个新的类,作为一个属性NSMutableArray
,但我想看看是否有办法用类别先做它。
非常感谢。
[Objective-C:类别中的实例变量]的可能重复(http://stackoverflow.com/questions/6162589/objective-c-instance-variable-in-category) – hfossli 2014-01-16 08:23:08