1

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

2
  • ok yeah like an array of arrays then. Commented Apr 19, 2011 at 19:35
  • C does not describe "NSMutable arrays"! Commented Apr 19, 2011 at 19:48

3 Answers 3

5

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];
Sign up to request clarification or add additional context in comments.

Comments

3

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]];

Comments

1
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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.