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?
转载于:https://stackoverflow.com/questions/586370/how-can-i-reverse-a-nsarray-in-objective-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?
转载于:https://stackoverflow.com/questions/586370/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