How can I reverse a NSArray in Objective-C?
For obtaining a reversed copy of an array, look at danielpunkass' solution using reverseObjectEnumerator
.
For reversing a mutable array, you can add the following category to your code:
@implementation NSMutableArray (Reverse)
- (void)reverse {
if ([self count] <= 1)
return;
NSUInteger i = 0;
NSUInteger j = [self count] - 1;
while (i < j) {
[self exchangeObjectAtIndex:i
withObjectAtIndex:j];
i++;
j--;
}
}
@end
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.