長列表若一次載入全部數據,不僅首屏變慢,記憶體也會吃不消。常見解法是分頁加載:每次只取一小批,當使用者滾到接近底部時再異步抓取下一頁。實作上有兩個關鍵:一是用計數器記錄目前頁碼,二是用一個結束旗標避免在沒有更多數據時持續發請求。
每次刷新時(分線程與下拉刷新共用),記得把狀態重置:
iListCountNum = 1; isEndList = NO;
核心在於 tableView:willDisplayCell:forRowAtIndexPath:。這個方法在每個 cell 即將顯示時被呼叫,我們只要判斷「目前是不是最後一行」且「列表尚未結束」,就能觸發下一頁的抓取。
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%d", indexPath.row);
if (indexPath.row == (m_tieziList.count - 1) && isEndList == NO)
{
iListCountNum++;
NSThread *InitThread = [[NSThread alloc] initWithTarget:self
selector:@selector(GetNewListThread:)
object:tableView];
[InitThread start];
}
}
-(void)GetNewListThread:(id)sender
{
NSMutableArray *array = [g_data GetTieziList:m_forumNode->forum_id
pageSize:9
pageNum:iListCountNum];
if (array.count == 0) {
isEndList = YES; // 沒有更多數據,停止後續請求
}
else {
isEndList = NO;
}
[m_tieziList addObjectsFromArray:array];
// 網絡請求必須回到主線程才能操作 UI
[self performSelectorOnMainThread:@selector(ReLoadTableData:)
withObject:(UITableView *)sender
waitUntilDone:NO];
}
-(void)ReLoadTableData:(id)sender
{
UITableView *table = (UITableView *)sender;
[table reloadData];
}
第一,網絡請求放在子線程執行,避免阻塞主線程造成界面卡頓;但 reloadData 這類 UI 操作必須切回主線程,否則未定義行為隨時可能出問題。
第二,isEndList 這個旗標是必需的。少了它,當用戶停在最後一行時 willDisplayCell 會被反覆觸發,瞬間發出大量重複請求。
第三,實務上還建議加上「加載中」的防重入標記。因為在異步請求返回之前,willDisplayCell 仍可能被多次呼叫,導致頁碼重複累加而漏抓數據。一個簡單的 isLoading 布爾值就能解決這個問題。