Rod*_*ddy 4 arrays objective-c
我正在尝试创建一个类,其中可以使用init参数在初始化时动态创建二维数组的宽度和高度.
我一直在网上浏览几个小时,找不到办法.
使用标准C语法[][]不允许使用变量来声明数组.在我看到的所有示例中,Objective C中的可变数组要求在创建时对对象进行硬编码.
有没有办法在对象中创建一个二维数组,并使用参数来定义创建时的大小?
希望有人能告诉我我错过了什么......
您可以通过编写类别来轻松完成此操作NSMutableArray:
@interface NSMutableArray (MultidimensionalAdditions)
+ (NSMutableArray *) arrayOfWidth:(NSInteger) width andHeight:(NSInteger) height;
- (id) initWithWidth:(NSInteger) width andHeight:(NSInteger) height;
@end
@implementation NSMutableArray (MultidimensionalAdditions)
+ (NSMutableArray *) arrayOfWidth:(NSInteger) width andHeight:(NSInteger) height {
return [[[self alloc] initWithWidth:width andHeight:height] autorelease];
}
- (id) initWithWidth:(NSInteger) width andHeight:(NSInteger) height {
if((self = [self initWithCapacity:height])) {
for(int i = 0; i < height; i++) {
NSMutableArray *inner = [[NSMutableArray alloc] initWithCapacity:width];
for(int j = 0; j < width; j++)
[inner addObject:[NSNull null]];
[self addObject:inner];
[inner release];
}
}
return self;
}
@end
Run Code Online (Sandbox Code Playgroud)
用法:
NSMutableArray *dynamic_md_array = [NSMutableArray arrayOfWidth:2 andHeight:2];
Run Code Online (Sandbox Code Playgroud)
要么:
NSMutableArray *dynamic_md_array = [[NSMutableArray alloc] initWithWidth:2 andHeight:2];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8914 次 |
| 最近记录: |