views:

7225

answers:

2

hey! i am new in objective c. i am trying to learn objective c. i would like to know how to declare two dimensional array of string type in objective c.

+15  A: 

You have a couple options. If you want to use an NSArray, you'll have to manually create the structure like this:

NSMutableArray *strings = [NSMutableArray array];
for(int i = 0; i < DESIRED_MAJOR_SIZE; i++)
{
    [strings addObject: [NSMutableArray arrayWithObject:@"" count:DESIRED_MINOR_SIZE]];
}

You can then use it like this:

NSString *s = [[strings objectAtIndex:i] objectAtIndex:j];

This is somewhat awkward to initialize, but it is the way to go if you want to use the NSArray methods.

An alternative is to use C arrays:

NSString *strings[MAJOR_SIZE][MINOR_SIZE] = {0}; // all start as nil

And then use it like this:

NSString *s = strings[i][j];

This is less awkward, but you have to be careful to retain and release values as you put them in to and remove them from the array. NSArray would do this for you but with C-style arrays, you need to do something like this to replace an array:

[strings[i][j] release];
strings[i][j] = [newString retain];

The other difference is that you can put nil in the C-style array, but not the NSArrays - you need to use NSNull for that. Also take a look here for more about NSString memory management.

Jesse Rusak
+1 for saving me a lot of typing.
Abizern
+3  A: 

If you want to declare and initialize a two-dimensional array of strings, you can do this:

NSArray *myArray = [NSArray arrayWithObjects:
                       [NSArray arrayWithObjects:@"item 1-1", @"item 1-2, nil],
                       [NSArray arrayWithObjects:@"item 2-1", @"item 2-2, nil],
                       [NSArray arrayWithObjects:@"item 3-1", @"item 3-2, nil],
                       nil];

This has the benefit of giving you an immutable array.

Steve McLeod