Let’s suppose I have a NSMutableArray like this:
Object 0
Object 1
Object 2
Object 3
Object 4
and would like to take Object 0 and Object 1 and move them behind Object 4:
Object 2
Object 3
Object 4
Object 0
Object 1
I have this rather long code to achieve the re-ordering of multiple objects, but I was wondering if there is a more straightforward / elegant way:
int from = 0;
int to = 5;
int lastIndexOfObjectsToBeMoved = 1;
NSMutableArray *objectsToBeMoved = [[NSMutableArray alloc] init];
for (int i = from; i < lastIndexOfObjectsToBeMoved; i++) {
object *o = [self.objects objectAtIndex:i];
[objectsToBeMoved addObject:o];
}
NSUInteger length = lastIndexOfObjectsToBeMoved-from;
NSRange indicesToBeDeleted = NSMakeRange(from, length);
[self.objects removeObjectsInRange:indicesToBeDeleted];
NSIndexSet *targetIndices = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(to, length)];
[self.objects insertObjects:objectsToBeMoved atIndexes:targetIndices];
Edit: sorry, I should have clarified, I’m not always moving objects to the very end, but would also like to be able to do things like moving object 2 and 3 to index 0.
Make an NSRange of the indexes you want to move to the back. Grab those objects with
subarrayWithRange, remove them withremoveObjectsInRange:and add them back to the end by callingaddObjectsFromArray:. This is a much more concise way of writing what you have.