views:

942

answers:

2

Hello!

Is there a way to create two dimensional NSArray without nesting arrays in the primitive format aFloatArray[][].

Thank you.

+3  A: 

Unfortunately not. To create a multi-dimensional NSArray:

NSArray *multiArray = [NSArray arrayWithObjects:
    [NSMutableArray array],
    [NSMutableArray array],
    [NSMutableArray array],
    [NSMutableArray array], nil];

// Add a value
[[multiArray objectAtIndex:1] addObject:@"foo"];

// get the value
NSString *value = [[multiArray objectAtIndex:1] objectAtIndex:0];

However, you can use C code in Objective-C (since it is a strict superset of C), if it fits your need you could declare the array as you had suggested.

pixel
If you're not using garbage collection, then you're leaking each of the arrays inside `multiArray`. To fix, use `[NSMutableArray array]` instead.
Dave DeLong
Really? It was my understanding that [NSMutableArray array] returned an autoreleased NSMutableArray, which would in turn be retained by the NSArray to which it is being added to!I will definatly look that up because if you are correct, I have a lot of code to go through lol
FatalMojo
Yes. The point is that the autoreleased object _is_ retained by the array it is added to. When the parent array is released, so are its contents. If you add `[NSMutableArray new]` to an array, its retain-count becomes `2`. When the parent array is released, each of its children still has a retain-count of `1`.
Jonathan Sterling
Try to avoid thinking in terms of the retain count. This can often be misleading. Think only in terms of ownership of objects. Since you obtained each of the four arrays with new, you are responsible for releasing them. You don't do that.Possible solutions:change [NSMutableArray new] to [[NSMutableArray new] autorelease] or [NSMutableArray array] oruse garbage collection (not an option on iPhone).
JeremyP
Oops, I realize now that I misread Dave's comment.In any case, thanks for the answers :) I was confused because I wasn't aware that NSObject had a 'new' class method and I assumed it was similar to NSArray's 'array' method.
FatalMojo
Dave -- very good point, especially on the iPhone. I'll definitely have to keep that in mind!
pixel
A: 

Can we specify count for [NSMutableArray new] Item...For Example, current example creates 4xN Array.....What If I want to specify count for the first dimention ??

Ashok
No. An NSArray can't have any empty slots. You can only increase the size by putting objects in it. You can signify an empty slot by putting [NSNull null] in the array.
JeremyP