关于TableView中图片的延时加载

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

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

重写如下方法

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

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

原因是

  UIImage *image = [self getImageForCellAtIndexPath:indexPath]; 

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

-(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];
}
目录
相关文章
|
1月前
|
开发者 iOS开发
介绍 UITableView 和 UICollectionView,它们的区别是什么?
介绍 UITableView 和 UICollectionView,它们的区别是什么?
91 0
|
1月前
|
监控
如何解决UICollectionView不能下拉刷新问题
如何解决UICollectionView不能下拉刷新问题
26 0
|
iOS开发
iOS 开发 - tableView内嵌scrollView时,在plus上滑动scrollView时和tableView有冲突
iOS 开发 - tableView内嵌scrollView时,在plus上滑动scrollView时和tableView有冲突
144 0
UIImageView 图片自适应大小
UIImageView 图片自适应大小
124 0
UITableView的创建
UITableView的创建
81 0
|
iOS开发
iOS UITableViewCell嵌套CollectionView,tableview和collectionview同时滑动bug修复
iOS UITableViewCell嵌套CollectionView,tableview和collectionview同时滑动bug修复
946 0
|
存储 iOS开发 搜索推荐