Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D arrays using NSMutableArray

I need to create a mutable two-dimensional array in Objective-C.

For example I have:

NSMutableArray *sections; NSMutableArray *rows; 

Each item in sections consists of an array rows. rows is an array that contains objects.

And I want to do something like this:

[ sections[i] addObject: objectToAdd]; //I want to add a new row 

In order have something like this: section 0, rows: obj1, obj2, obj3 section 1, rows: obj4, obj5, obj6, obj 7...

Is there a way to do that in Objective-C?

like image 364
Ilya Suzdalnitski Avatar asked Apr 07 '09 09:04

Ilya Suzdalnitski


Video Answer


1 Answers

First, you must allocate and initialize your objects before use, something like: NSMutableArray * sections = [[NSMutableArray alloc] initWithCapacity:10]; For the rows, you need one object for each, not a single NSMutableArray * rows;

Second, depending on whether you're using Xcode 4.4+ (which introduced subscripting, a.k.a section[i] & section[i] = …) you may have to use [sections objectAtIndex:i] for reading and [section replaceObjectAtIndex:i withObject: objectToAdd] for writing.

Third, an array cannot have holes, i.e., obj1, nil, obj2. You must provide actual object to every index. If you do need to put nothing, you can use NSNull object.

Moreover, don't forget that you can also store Objective-C objects in plain C arrays:

id table[lnum][rnum]; table[i][j] = myObj; 
like image 193
mouviciel Avatar answered Nov 07 '22 09:11

mouviciel