Add this in a category to NSMutableArray:
- (void) invertArray{
NSUInteger operationCount = self.count / 2;
NSUInteger lastIndex = self.count - 1;
id tmpObject;
for (int i = 0; i < operationCount; i++){
tmpObject = [self objectAtIndex:i];
[self replaceObjectAtIndex:i withObject:[self objectAtIndex:lastIndex - i]];
[self replaceObjectAtIndex:lastIndex - i withObject:tmpObject];
}
}
This will invert the array without creating any new array. Moreover, it's fairly efficient, needing only to iterate over half the array.
If you need to arrange the tableView while you rearrange the array, use this method (again as a category to NSMutableArray):
- (void) invertArrayWithOperationBlock:(void(^)(id object, NSUInteger from, NSUInteger to))block{
NSUInteger operationCount = self.count / 2;
NSUInteger lastIndex = self.count - 1;
id tmpObject1;
id tmpObject2;
for (int i = 0; i < operationCount; i++){
tmpObject1 = [self objectAtIndex:i];
tmpObject2 = [self objectAtIndex:lastIndex - i];
[self replaceObjectAtIndex:i withObject:tmpObject2];
[self replaceObjectAtIndex:lastIndex - i withObject:tmpObject1];
if (block){
block(tmpObject1, i, lastIndex - i);
block(tmpObject2, lastIndex - i, i);
}
}
}
This will allow you to pass a block to the method to execute code for each move. You can use this to animate the rows in your table view. For example:
[self.tableView beginUpdates];
[array invertArrayWithOperationBlock:^(id object, NSUInteger from, NSUInteger to){
[self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:from inSection:0] toIndexPath:[NSIndexPath indexPathForRow:to inSection:0];
}];
[self.tableView endUpdates];