How can I reverse a NSArray in Objective-C?

Andy Jacobs picture Andy Jacobs · Feb 25, 2009 · Viewed 141.9k times · Source

I need to reverse my NSArray.

As an example:

[1,2,3,4,5] must become: [5,4,3,2,1]

What is the best way to achieve this?

Answer

danielpunkass picture danielpunkass · Feb 25, 2009

There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator method on NSArray, and the allObjects method of NSEnumerator:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];

allObjects is documented as returning an array with the objects that have not yet been traversed with nextObject, in order:

This array contains all the remaining objects of the enumerator in enumerated order.