開發時常會遇到需要載入大量資料的情況,例如頻繁地請求網路、載入大量圖片。此時如果等所有圖片都下載完才去刷新 TableView,使用者體驗會非常糟糕。
要解決這個問題,關鍵在於把耗時的載入工作放到子執行緒,完成一批後再回主執行緒刷新介面。個人做法是:先顯示前 n 張圖片(此處 n=5),多餘的圖片則放到子執行緒中處理並逐步載入。
當資料量超過 5 筆時,啟動背景執行緒:
if([array count]>5)
{
[self performSelectorInBackground:@selector(show_list_item_in_background:) withObject:array];
}
若想每載入 m 張圖片就刷新一次 TableView,可以在子執行緒中週期性地回主執行緒更新:
- (void)show_list_item_in_background:(NSArray*)array
{
int index = 5;
int second_run = [array count];
while(index < second_run)
{
NSDictionary *dictionary = [array objectAtIndex:index];
[self get_and_show_more:dictionary];
index++;
if(index > 5 && index % 5== 0)
{
[self performSelectorOnMainThread:@selector(reload_table_view_on_main_thread) withObject:nil waitUntilDone:NO];
}
}
[table_view reloadData];
[activity_view stopAnimating];
}
主執行緒只要呼叫 reload_table_view_on_main_thread 即可安全地刷新 TableView:
- (void)reload_table_view_on_main_thread
{
[table_view reloadData];
}
這個範例的核心觀念是:UI 更新必須在主執行緒進行,而資料載入則可交給子執行緒,兩者透過 performSelectorOnMainThread: 溝通,兼顧效能與流暢度。