Reputation: 22519
I want to make a 2D array like this
[[1,2,3],[94,22],[2,4,6],[1,3,5,6]]
What is the best way to do this for iOS using NSMutable arrays
Upvotes: 1
Views: 7496
Reputation: 2276
NSArray *array = @[@[@1, @2, @3],
@[@94, @22],
@[@2, @4, @6],
@[@1, @3, @5, @6]];
NSMutableArray *arrayM = [[NSMutableArray alloc] init];
for(NSArray *nextArray in array)
arrayM addObject:[[NSMutableArray alloc] initWithArray:nextArray];
Upvotes: 1
Reputation: 124997
Neither C nor Objective-C truly support 2D arrays. Instead, in either language, you can create an array of arrays. Doing this in C gives you the same effect as a 2D array of ints with 2 rows and 3 columns, or vice versa:
int foo[2][3];
You can do something similar in Objective-C, but since you can't create objects statically, and you can't fix the size of a mutable array, and NSMutableArray holds object pointers rather than ints, it's not exactly the same:
NSMutableArray *foo = [NSMutableArray array];
for (short i = 0; i < 2; i++)
[foo addObject:[NSMutableArray array]];
Upvotes: 3
Reputation: 1206
You cannot create a static 2D array with differently sized rows.
Perhaps you can use NSArrays instead of C arrays to achieve this.
edit: This is tedious, but you can try:
NSArray *array1 = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:1],[NSNumber numberWithInt:3],nil];
And so on for each array, then
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
[mutableArray addObject:array1];
Upvotes: 5