Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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).</p> <p>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:</p> <pre><code>NSMutableArray *strings = [NSMutableArray array]; for(int i = 0; i &lt; DESIRED_MAJOR_SIZE; i++) { [strings addObject: [NSMutableArray arrayWithObject:@"" count:DESIRED_MINOR_SIZE]]; } </code></pre> <p>Or, using array literals, you can get an <em>immutable</em> version like this:</p> <pre><code>NSArray *strings = @[ @[ @"A", @"B", @"C" ], @[ @"D", @"E", @"F" ], @[ @"G", @"H", @"I" ] ] </code></pre> <p>You can then use it like this:</p> <pre><code>NSString *s = [[strings objectAtIndex:i] objectAtIndex:j]; </code></pre> <p>This is somewhat awkward to initialize, but it is the way to go if you want to use the NSArray methods.</p> <p>An alternative is to use C arrays:</p> <pre><code>NSString *strings[MAJOR_SIZE][MINOR_SIZE] = {0}; // all start as nil </code></pre> <p>And then use it like this:</p> <pre><code>NSString *s = strings[i][j]; </code></pre> <p>This is less awkward, but you have to be careful to <em>retain/copy</em> and <em>release</em> 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:</p> <pre><code>[strings[i][j] release]; strings[i][j] = [newString retain]; </code></pre> <p>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 <em><a href="https://stackoverflow.com/questions/329977/cocoa-memory-management-with-nsstring">Cocoa: Memory management with NSString</a></em> for more about NSString memory management.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload