您的位置:首页 > 移动开发 > IOS开发

iOS开发中如何解决TableView中图片延时加载

2013-11-08 17:05 465 查看
IOS开发中如何解决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]; 
5
    
}
这虽然解决了延时加载的问题, 但当网速很慢, 或者图片很大时(假设,虽然一般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]; 
8
    
}
然后再新开一个线程去做这件事情

1
-
(
void
)tableView:(UITableView
*)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
2
    
3
        
[NSThread
detachNewThreadSelector:@selector(updateImageForCellAtIndexPath:) toTarget:self withObject:indexPath]; 
4
    
}
同理当我们需要长时间的计算时,也要新开一个线程 去做这个计算以避免程序处于假死状态

以上代码只是示例, 还可以改进的更多, 比如从网上down下来一次后就将图片缓存起来,再次显示的时候就不用去下载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uitableview ios