关于TableView中图片的延时加载(转)
經(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下來一次后就將圖片緩存起來,再次顯示的時候就不用去下載。
轉(zhuǎn)載于:https://www.cnblogs.com/cherri/archive/2010/08/26/1808816.html
總結(jié)
以上是生活随笔為你收集整理的关于TableView中图片的延时加载(转)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WIN7系统更新安装补丁“此更新不适用于
- 下一篇: 关于oneNote插件加载不显示的问题(