Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 have been looking through the web for hours and cannot find a way.

Using a standard C syntax [][] does not allow for a variable to be used to declare the array. The mutable arrays within Objective C, in all examples I have seen, require the objects to be hard coded at the time of creation.

Is there a way of creating a 2 dimensional array within an object with parameters to define the sizes at the point of creation?

Hoping someone can tell me what I am missing...

like image 331
Roddy Avatar asked Dec 29 '22 01:12

Roddy


1 Answers

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];
like image 117
Jacob Relkin Avatar answered May 19 '23 04:05

Jacob Relkin