IOS開發(fā)中如何解決TableView中圖片延時加載
IOS開發(fā)中如何解決TableView中圖片延時加載是本文要介紹的內(nèi)容,主要是來學(xué)習(xí)TableView加載圖片的問題。具體內(nèi)容來看本文詳細內(nèi)容。
經(jīng)常我們會用tableView顯示很多條目, 有時候需要顯示圖片, 但是一次從服務(wù)器上取來所有圖片對用戶來浪費流量, 對服務(wù)器也是負擔(dān).最好是按需加載,即當(dāng)該用戶要瀏覽該條目時再去加載它的圖片。
重寫如下方法
- - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
- {
- UIImage *image = [self getImageForCellAtIndexPath:indexPath]; //從網(wǎng)上取得圖片
- [cell.imageView setImage:image];
- }
這雖然解決了延時加載的問題, 但當(dāng)網(wǎng)速很慢, 或者圖片很大時(假設(shè),雖然一般cell中的圖很小),你會發(fā)現(xiàn)程序可能會失去對用戶的響應(yīng).
原因是
- UIImage *image = [self getImageForCellAtIndexPath:indexPath];
這個方法可能要花費大量的時間,主線程要處理這個method.
所以失去了對用戶的響應(yīng).
所以要將該方法提出來:
- - (void)updateImageForCellAtIndexPath:(NSIndexPath *)indexPath
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- UIImage *image = [self getImageForCellAtIndexPath:indexPath];
- UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
- [cell.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
- [pool release];
- }
然后再新開一個線程去做這件事情
- - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
- {
- [NSThread detachNewThreadSelector:@selector(updateImageForCellAtIndexPath:) toTarget:self withObject:indexPath];
- }
同理當(dāng)我們需要長時間的計算時,也要新開一個線程 去做這個計算以避免程序處于假死狀態(tài)
以上代碼只是示例, 還可以改進的更多, 比如從網(wǎng)上down下來一次后就將圖片緩存起來,再次顯示的時候就不用去下載。
小結(jié):IOS開發(fā)中如何解決TableView中圖片延時加載的內(nèi)容介紹完了,希望通過本文的學(xué)習(xí)能對你有所幫助!