开发者

Initializing multidimensional NSArray for iPhone devel

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

I ini开发者_JAVA技巧tialize 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜