views:

25

answers:

2

Hello, i'm starting in iPhone devel and i need to use a multidimensional array.

I init it using:

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

when i try to assign values to n-th cell like:

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

App hangs because of index 4 beyond bounds [0 .. 1].

Which is the correct way to init my multi array?

Thanks in advance and greetings c.

+1  A: 

What you did is creating an array containing two objects: two other arrays. You're actually asking for the 5th object within this "super-array", which won't work because there is none.

By the way, even if you create an array specifying a capacity, it is still empty. Specifying a capacity merely allocs enough memory for the array to hold at least the given number of objects. If you add no objects, it would still make your app crash if you'd ask for, say, the 10th object.

Toastor
+1  A: 

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.

jv42
Thank you very much, it worked perfectly for me !
Cris