簡體   English   中英

調用reloadData后出現UITableView性能問題

[英]UITableView performance issue after calling reloadData

我是一名Android開發人員,負責我的第一個iOS項目。 我有一個顯示近37,500行的UITableView。 雜貨店中每件商品一行。 該列表有3列,一列包含項目名稱,另外兩列包含其他重要數據。 這些列是可排序的,為了處理排序,我根據需要對數據數組進行排序,並在完成數組排序后調用[tableView reloadData] 這樣可以正常工作,除非在重新加載主線程鎖定工作的數據后至少有幾秒鍾的延遲。 我對列出性能並不陌生,因為我必須在Android中多次制作流暢的列表。 所以我可以告訴我,實際上並沒有做太多事情。 我唯一能想到的就是我的數組中的大量項目。 這是相關代碼:

以下是我重寫的表格方法:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return [self.data count];
 }

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"CustomCell";
ReplenishListCell *cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
    cell = [[ReplenishListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

NSMutableDictionary *dictData = [self.data objectAtIndex:indexPath.row];

cell.nameLabel.text = dictData[@"item-description"];
cell.firstLicationColumnLabel.text = dictData[@"store-count"];
cell.secondLicationColumnLabel.text = dictData[@"other-count"];

return cell;
}

-(void)tableView:(UITableView *)replenishTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self showActivityIndicator];

ReplenishListCell *cell = (ReplenishListCell*) [replenishTableView cellForRowAtIndexPath:indexPath];
NSString *nameClicked = cell.nameLabel.text;

[database getItemByName:nameClicked :self];
}

這是我用來對數組進行排序的方法:

-(void) sortArray:(NSString *) dictionaryKey {
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:dictionaryKey ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [data sortedArrayUsingDescriptors:sortDescriptors];

[data removeAllObjects];
[data addObjectsFromArray:sortedArray];

[self.tableView reloadData];
}

在調用[self.tableView reloadData]之后,我沒有任何性能問題。 所以我想知道是否有一些我缺少的東西,或者除了reloadData之外還有更好的方法來重新加載數據? 任何幫助將不勝感激。 我現在花了幾個小時調試和谷歌搜索,我還沒有提出解決方案。

UI懸掛的一個可能原因是您正在刪除並添加兩個陣列之間的所有37.5k對象。

嘗試改變這個:

[data removeAllObjects];  
[data addObjectsFromArray:sortedArray];

對此:

data = sortedArray;

對於大型操作,您應該使用后台隊列,而不是在主隊列上執行該操作並阻止UI。 在后台操作中可以獲得數據后,您可以在主隊列上調用reloadData:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            [self sortArray:<# your key #>];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
});

同樣考慮使用保羅的建議,如前面的答案。

你的代碼看起來不錯。 就像@paulrehkugler在他的回答中所說,你可以在data = sortedArray中對數組進行排序。

根據您擁有的數據量,請考慮在后台線程中對數據進行預排序 根據我的計算,如果你保留3個不同排序順序的數組,那么37,500個對象需要150K的內存。 因此,當用戶選擇按特定列排序時,您已經對數據進行了排序,並且您只需交換用作數據源的數組。 對於用戶來說,那么分類幾乎是瞬間出現的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM