Objective-c – How to reverse a NSArray in Objective-C

nsarrayobjective c

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?

Best Answer

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.