假设我有这样一个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。
发布于 2012-07-24 09:08:36
创建要移到后面的索引的NSRange。用subarrayWithRange获取这些对象,用removeObjectsInRange:删除它们,并通过调用addObjectsFromArray:将它们添加回末尾。这是一种更简洁的写作方式。
发布于 2013-02-01 11:17:54
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];我希望这对你有帮助
https://stackoverflow.com/questions/11627434
复制相似问题