I'm trying to achieve something like this
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"A",@"B",@"C", nil]; NSLog(@"Array: %@", myArray); //logs A, B, C. //reverse code here NSLog(@"Array: %@", myArray); //logs C, B, A
The code isn't exact, just a demo. But you get the idea.
Any way to do this?
The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...
You can reverse a NSArray by writing your own loop iterating from the end towards the beginning and using a second array to add the items in reverse order. Or you can simply use - (NSEnumerator *)reverseObjectEnumerator from the NSArray class.
The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .
Simply use;
NSArray* reversed = [[myArray reverseObjectEnumerator] allObjects];
The order is documented to be correct:
This array contains all the remaining objects of the enumerator in enumerated order [emphasis added].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With