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?
Sommaire |
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?
@implementation NSArray (Reverse) - (NSArray *)reversedArray { NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]]; NSEnumerator *enumerator = [self reverseObjectEnumerator]; for (id element in enumerator) { [array addObject:element]; } return array; } @end @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
License : cc by-sa 3.0
http://stackoverflow.com/questions/586370/how-can-i-reverse-a-nsarray-in-objective-c