Search code examples
iphoneobjective-cmemory-managementmultidimensional-arraynsarray

Initializing multidimensional NSArray for iPhone devel


I'm starting with iPhone development and I need to use a multidimensional array.

I initialize it using:

NSArray *multi=[NSArray 
  arrayWithObjects:[NSMutableArray arrayWithCapacity:13],
  [NSMutableArray array],nil];

But when I try to assign values to n-th cell like this:

[[multi objectAtIndex:4] addObject:@"val"];

The app hangs because index 4 is beyond the bounds [0 .. 1].

Which is the correct way to init my multi-array? Thanks in advance and greetings.


Solution

  • I guess you want to create a NSMutableArray of NSMutableArrays:

    NSMutableArray *multi = [NSMutableArray arrayWithCapacity: 13];
    for (int i = 0; i != 13; i++)
    {
        NSMutableArray *array = [NSMutableArray arrayWithCapacity: 10];
        [multi insertObject: array atIndex: 0];
    }
    

    After that, your call is valid.

    EDIT: as a side note, capacity != count, as would be in .NET or C++'s STL if you know these.