2012-02-29 64 views
0

我填充UITableView中的NSMUtableArray項目列表。顛倒UITableView中的項目列表

我想知道是否有一個函數可以用來反轉顯示列表的順序?

我知道,我可能只需要創建一個新的列表用倒置的循環但那也是莫名其妙地浪費內存

謝謝

回答

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也可能有所幫助。

+0

我也可以這樣做,只是認爲可能存在一個per-buit函數或其他... – user1051935 2012-02-29 14:48:23

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