假设我有一个像这样的NSMutableArray:
对象0 对象1 对象2 对象3 对象4
并希望将对象0和对象1移动到对象4后面:
对象2 对象3 对象4 对象0 对象1
我有这个相当长的代码来实现多个对象的重新排序,但我想知道是否有更直接/更优雅的方式:
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];
编辑:抱歉,我应该澄清一下,我并不总是将对象移动到最后,但也希望能够将对象2和3移动到索引0。
答案 0 :(得分:3)
创建要移动到后面的索引的NSRange。使用subarrayWithRange
抓取这些对象,使用removeObjectsInRange:
将其删除,然后通过调用addObjectsFromArray:
将其添加回最后。这是一种更简洁的写作方式。
答案 1 :(得分:0)
rowIndexes是一个NSIndexSet,包含您喜欢移动的对象
行是索引目的地
NSArray *objectsToMove = [your_array objectsAtIndexes: rowIndexes];
// If any of the removed objects come before the row
// we want to decrement the row appropriately
row -= [rowIndexes countOfIndexesInRange: (NSRange){0, row}];
[your_array removeObjectsAtIndexes:rowIndexes];
[your_array replaceObjectsInRange: (NSRange){row, 0}
withObjectsFromArray: objectsToMove];
我希望这有助于你