Two-dimensional Array

Every array in Objective-C is one-dimensional. To simulate a two-dimensional array, we create an array of arrays. The following app simulates a 4 × 3 array of strings with four rows and three columns. As usual, the numbers are zero-based.

objectAtIndex: returns an id, and any message (in this case, count) can be sent without a cast to an id. But the count property of an id would have required a cast.

I used printf instead of NSLog because NSLog always outputs a newline. The first argument of printf must be a string without a @. Within this string, printf does not know about the @% format.

Source code in Twod.zip

  1. main.m

Output

2011-12-08 13:12:03.942 Twod[58127:207] a.count == 4
2011-12-08 13:12:03.944 Twod[58127:207] [[a objectAtIndex: 0] count] == 3
2011-12-08 13:12:03.944 Twod[58127:207] [[a objectAtIndex: 1] count] == 3
2011-12-08 13:12:03.944 Twod[58127:207] [[a objectAtIndex: 2] count] == 3
2011-12-08 13:12:03.945 Twod[58127:207] [[a objectAtIndex: 3] count] == 3

(row 0, col 0)	(row 0, col 1)	(row 0, col 2)
(row 1, col 0)	(row 1, col 1)	(row 1, col 2)
(row 2, col 0)	(row 2, col 1)	(row 2, col 2)
(row 3, col 0)	(row 3, col 1)	(row 3, col 2)

Things to try

  1. Do all the rows have to have the same number of elements?