Luca
Luca

Reputation: 20959

Is it possible to make an array of arrays

I need to make an array, in which each object is a NSArray:

 NSMutableArray *AberdeenStores=[NSMutableArray alloc];

AberdeenStores=[AberdeenStores initWithObjects:[[NSArray alloc]initWithObjects:@"Aberdeen Name Store 1",@"Aberdeen Adress Store 1",@"Aberdeen Telephone store 1","", nil],[NSArray arrayWithObjects:@"Aberdeen Name Store 2",@"Aberdeen Adress Store 2",@"Aberdeen Telephone store 2", nil],[[NSArray alloc ]initWithObjects:@"Aberdeen Name Store 3",@"Aberdeen Adress Store 3",@"Aberdeen Telephone store 3", nil], nil];

This seems causing crash. What is wrong please? Thanx in advance.

Upvotes: 1

Views: 104

Answers (3)

brandontreb
brandontreb

Reputation: 397

Here is a more scalable solution:

// Top Level Array
NSMutableArray *array = [[NSMutableArray alloc] init];
int size = 10;    

// Build sub level arrays
for(int i = 0; i < size; i++)
{
    NSMutableArray *subArray = [[NSMutableArray alloc] init];
    [array addObject:subArray];
}

// You can now use it like this:
[[array objectAtIndex:0] addObject:someObject];
NSObject *someObject = [[array objectAtIndex:0] objectAtIndex:0];

Hope that helps!

Upvotes: 1

Thomas Clayson
Thomas Clayson

Reputation: 29935

You're using variables and objects and all sorts wrong here. This is the best way to do what you're trying to do and will layout nicely and be better for maintainability.

NSMutableArray *AberdeenStores = [[NSMutableArray alloc] init];
[AberdeenStores addObject:[NSArray arrayWithObjects:@"Aberdeen Name Store 1",@"Aberdeen Adress Store 1",@"Aberdeen Telephone store 1",@"", nil]];
[AberdeenStores addObject:[NSArray arrayWithObjects:@"Aberdeen Name Store 2",@"Aberdeen Adress Store 2",@"Aberdeen Telephone store 2",@"", nil]];
[AberdeenStores addObject:... keep adding objects as you please];

Upvotes: 0

mprivat
mprivat

Reputation: 21912

You just have a typo in there. Replace "" with @"" in the first sub-array

NSMutableArray *AberdeenStores=[NSMutableArray alloc];

AberdeenStores=[AberdeenStores initWithObjects:[[NSArray alloc]initWithObjects:@"Aberdeen Name Store 1",@"Aberdeen Adress Store 1",@"Aberdeen Telephone store 1",@"", nil],[NSArray arrayWithObjects:@"Aberdeen Name Store 2",@"Aberdeen Adress Store 2",@"Aberdeen Telephone store 2", nil],[[NSArray alloc ]initWithObjects:@"Aberdeen Name Store 3",@"Aberdeen Adress Store 3",@"Aberdeen Telephone store 3", nil], nil];

Upvotes: 4

Related Questions