IOS 延时加载TableView中Cell中的图片

TableView图片延时加载是本文要介绍的内容,经常我们会用tableView显示很多条目,有时候需要显示图片。但是一次性从服务器上取来所有图片对用户来浪费流量,对服务器也是负担,最好是按需加载,即当该用户要浏览该条目时再去加载经常我们会用tableView显示很多条目。

有时候需要显示图片, 但是一次从服务器上取来所有图片对用户来浪费流量,,对服务器也是负担.最好是按需加载,即当该用户要浏览该条目时再去加载它的图片。

重写如下方法

 
 
  1. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     UIImage *image = [self getImageForCellAtIndexPath:indexPath];  //从网上取得图片  
  4.     [cell.imageView setImage:image];  

这虽然解决了延时加载的问题, 但当网速很慢, 或者图片很大时(假设,虽然一般cell中的图很小),你会发现程序可能会失去对用户的响应.

原因是

 
 
  1. UIImage *image = [self getImageForCellAtIndexPath:indexPath]; 

这个方法可能要花费大量的时间,主线程要处理这个method,所以失去了对用户的响应.

所以要将该方法提出来:

 
 
  1. - (void)updateImageForCellAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  4.     UIImage *image = [self getImageForCellAtIndexPath:indexPath];  
  5.     UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];  
  6.     [cell.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];  
  7.     [pool release];  

然后再新开一个线程去做这件事情

 
 
  1. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     [NSThread detachNewThreadSelector:@selector(updateImageForCellAtIndexPath:) toTarget:self withObject:indexPath];  

同理当我们需要长时间的计算时,也要新开一个线程 去做这个计算以避免程序处于假死状态

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值