Objective C - Create a multi-dimensional array with the dimensions specified at initialisation

前端 未结 3 805
北恋
北恋 2020-12-19 15:57

I am trying to create a class where the width and height of a 2 dimensional array can be dynamically created at the point of initialisation with init parameters.

I h

3条回答
  •  甜味超标
    2020-12-19 16:17

    You can do this quite easily by writing a category on 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
    

    Usage:

    NSMutableArray *dynamic_md_array = [NSMutableArray arrayOfWidth:2 andHeight:2];
    

    Or:

    NSMutableArray *dynamic_md_array = [[NSMutableArray alloc] initWithWidth:2 andHeight:2];
    

提交回复
热议问题