Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a two dimensional array of string type in Objective-C?

Tags:

How do I declare a two dimensional array of string type in Objective-C?

like image 748
ashish Avatar asked Mar 12 '09 11:03

ashish


People also ask

Can you declare a 2D array of objects?

Java Two Dimensional Array of Objects We can declare a 2D array of objects in the following manner: ClassName[][] ArrayName; This syntax declares a two-dimensional array having the name ArrayName that can store the objects of class ClassName in tabular form.

How do you declare an array in Objective C?

Declaring Arrays To declare an array in Objective-C, we use the following syntax. type arrayName [ arraySize ]; type defines the data type of the array elements.


1 Answers

First, you might consider using a class to hold your inner array's strings, or loading it from a plist file (in which it is easy to make an 2d array of strings).

For direct declarations, you have a couple of 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]]; } 

Or, using array literals, you can get an immutable version like this:

NSArray *strings = @[ @[ @"A", @"B", @"C" ], @[ @"D", @"E", @"F" ], @[ @"G", @"H", @"I" ] ] 

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/copy and release values as you put them in to and remove them from the array. (Unless you're using ARC, of course!) 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 at Stack Overflow question Cocoa: Memory management with NSString for more about NSString memory management.

like image 160
Jesse Rusak Avatar answered Sep 18 '22 15:09

Jesse Rusak