Search code examples
iphoneobjective-carraysprogramming-languagesnsmutablearray

Dynamically create arrays at runtime and add to another array


I am working on a small isometric engine for my next iPhone game. To store the map cells or tiles I need a 2 dimensionel array. Right now I am faking it with a 1-dimensionel, and it is not good enough anymore.

So from what I have found out looking around the net is that in objective-c I need to make an array of arrays. So here is my question: How do I dynamicly create arrays at runtime based on how many map-rows I need?

The first array is easy enough:

NSMutableArray *OuterArray = [NSMutableArray arrayWithCapacity:mapSize];

now I have the first array that should contain an array for each row needed. Problem is, it can be 10 but it can also be 200 or even more. So I dont want to manually create each array and then add it. I am thinking there must be a way to create all these arrays at runtime based on input, such as the chosen mapsize.

Hope you can help me Thanks in advance Peter


Solution

  • The whole point of NSMutableArray is that you don't care. Initialize both dimensions with an approximate size and then add to them. If your array grows beyond your initial estimate the backing storage will be increased to accomodate it. This counts for both your columns (first order array), and rows (second order array).


    EDIT

    Not sure what you meant in your comment. But this is one way to dynamically create a 2-dimensional mutable array in Objective-C.

    NSUInteger columns = 25 ; // or some random, runtime number
    NSUInteger rows = 50;     // once again, some random, runtime number
    
    NSMutableArray * outer = [NSMutableArray arrayWithCapacity: rows];
    
    for(NSUInteger i; i < rows; i++) {
        NSMutableArray * inner = [NSMutableArray arrayWithCapacity: columns];
        [outer addObject: inner];
    }
    
    // Do something with outer array here