0

I have made multidemensional arrays in c++ but I am confused on how to do this in objective c because it is a modified version of c. How would I go about making a multidimensional array in Objective C?

random_0620
  • 1,636
  • 5
  • 23
  • 44

1 Answers1

2
NSArray *twoDArray = @[@[@"0.0", @"0.1"], 
                       @[@"1.0", @"1.1", @"1.2"], 
                       @[@"2.0", @"2.1", @"2.2"]
                     ];

Access it like:

// result = "0.1"
NSString *result = twoDArray[0][1];

// result = "1.2"
result = twoDArray[1][2];

// result = "2.0"
result = twoDArray[2][0];

You don't really use them much differently than you would in C, although (per the comments) they do function quite differently. Objective-C is also not really a modified version of C. It is everything that C is, plus more. So it really does not modify anything about C.

This syntax (for creating and accessing the array values) is also relatively new, for more information you can look at the documentation and this answer, which both outline some other features of Objective-C literals.

Community
  • 1
  • 1
Firo
  • 15,448
  • 3
  • 54
  • 74
  • It may not look different than a plain array in C but really is a lot different. Would be worth pointing out that this is all new syntax. Also, I'd still prefer something like `float x[4][4];` in most cases. – s.bandara Oct 27 '13 at 01:07
  • 1
    Quite a substantial difference. One is a jagged array (Objective C array of arrays), while the other is a multidimensional array (C). Memory is laid completely differently. – Léo Natan Oct 27 '13 at 01:08
  • Thank you both, I (believe I have) corrected by answer. If you want to modify anything feel free :) – Firo Oct 27 '13 at 01:11
  • @s.bandara A pointer array is quite difficult to manage, especially with ARC. If a "multidimensional" array is needed in the sense of C/C++, it can be easily achieved with one long sequential array, then some arithmetics for the indices. – Léo Natan Oct 27 '13 at 01:14
  • @s.bandara the syntax is about 1.5 years old, but I will add a note about it in my answer. – Firo Oct 27 '13 at 01:21
  • @LeoNatan How is `NSObject *x[4][4]` different from `NSObject *x[16]` with respect to ARC? To my knowledge, the compiler will do the index arithmetics for you in the former case, and otherwise both are identical, aren't they? – s.bandara Oct 27 '13 at 01:25
  • @s.bandara Between those two examples, no difference. But from experience pointer array don't play very well with ARC. – Léo Natan Oct 27 '13 at 08:26