Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reverse the order of objects in an NSMutableArray? [duplicate]

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?

like image 997
Sam Jarman Avatar asked Jan 16 '10 23:01

Sam Jarman


People also ask

Is NSMutableArray ordered?

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...

How do you reverse an NSArray?

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.

What is NSMutableArray?

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 .


1 Answers

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].

like image 157
EEE Avatar answered Oct 21 '22 20:10

EEE