Objective C - 使用初始化时指定的尺寸创建一个多维数组

Rod*_*ddy 4 arrays objective-c

我正在尝试创建一个类,其中可以使用init参数在初始化时动态创建二维数组的宽度和高度.

我一直在网上浏览几个小时,找不到办法.

使用标准C语法[][]不允许使用变量来声明数组.在我看到的所有示例中,Objective C中的可变数组要求在创建时对对象进行硬编码.

有没有办法在对象中创建一个二维数组,并使用参数来定义创建时的大小?

希望有人能告诉我我错过了什么......

Jac*_*kin 6

您可以通过编写类别来轻松完成此操作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)

  • 这是一个想法 - 在实例init中有一个超级容量调用; NSMutableArray的超级是NSArray,它没有容量设置.这应该是对自我的呼唤而不是超级吗? (3认同)
  • +1但是为了DRY和Cocoa编码约定,我将工厂方法体更改为:`return [[[self alloc] initWithWidth:width andHeight:height] autorelease];` (2认同)