Reputation: 12194
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.
Upvotes: 1
Views: 1156
Reputation: 8593
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.
Upvotes: 2
Reputation: 8990
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.
Upvotes: 2