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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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.
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.
Thank you both, I (believe I have) corrected by answer. If you want to modify anything feel free :)
@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.
@s.bandara the syntax is about 1.5 years old, but I will add a note about it in my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.