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