反转UITableView中的项目列表

时间:2012-02-29 14:41:00

标签: objective-c uitableview nsmutablearray xcode4.2

我在UITableView中填充了一个NSMUtableArray项目列表。

我想知道是否有一个函数可以用来反转显示列表的顺序?

我知道我可能只是创建一个带有倒置for循环的新列表,但这在某种程度上浪费了内存

谢谢

3 个答案:

答案 0 :(得分:3)

为什么不反转在数据源方法中获取数据的顺序?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  NSUInteger dataItemIndex = self.inverted ? (self.dataItems.count - 1 - indexPath.row) : indexPath.row;

  // Fetch item at index and return cell ...
}

我担心没有内置方法来反转数组的对象顺序。这question也可能有所帮助。

答案 1 :(得分:1)

你可以看看:

NSSortDescriptor

来自文档:NSSortDescriptor的实例通过指定用于比较对象的属性,用于比较属性的方法以及比较是升序还是降序来描述订购对象的基础。

指定应如何排列表视图中的元素(请参阅sortDescriptors)

虽然如果它只是一个简单的翻转上升到下降我可能只是这样做:

- (NSMutableArray *)reverseArrayOrder {
    NSMutableArray *reversedArray = [NSMutableArray arrayWithCapacity:[self count]];
    NSEnumerator *enumerator = [self reverseObjectEnumerator];
    for (id element in enumerator) {
        [reversedArray addObject:element];
    }
    return reversedArray;
}

答案 2 :(得分:0)

将此类别添加到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];
    }
}

这将反转数组而不创建任何新数组。而且,它非常有效,只需迭代一半的数组。

如果在重新排列数组时需要排列tableView,请使用此方法(再次作为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);
        }
    }
}

这将允许您将块传递给方法以执行每次移动的代码。您可以使用它来为表视图中的行设置动画。例如:

[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];