**
1.用两个字典一个装image,一个装下载线程operations;
2.判断有无图片,若无,判断有无下载线程,若无创建下载;
3.把创建的线程放入线程字典中,以链接为key,把下载的图片放入图片字典中,同样以链接为key;
4下载执行结束把下载线程中的下载移除
//存放下载数据的队列
NSOperationQueue*_opaque;
//保存图片的字典
NSMutableDictionary*_image;
//保存operation的字典(url-key operation-Value)
NSMutableDictionary*_operations;(在control 界面以上三个最好在。m文件中写成@property(nonatomic,strong)形势)**
1.***************************************
UIImage*image=_image[dict[@"imgurl"]];
if (image)
{
//说明图片下载成功
cell.imageView.image=image;
}
else
{//说明图片没下载成功
cell.imageView.image=[UIImage imageNamed:@"share"];
[self download:dict[@"imgurl"] index:indexPath];
}
2.//写download方法
-(void)download:(NSString*)urlString index:(NSIndexPath*)indexPath
{
NSBlockOperation*operation=_operations[urlString];
if (operation)
{ return;}
operation=[NSBlockOperation blockOperationWithBlock:^{
NSURL*url=[NSURL URLWithString:urlString];
NSData*data=[NSData dataWithContentsOfURL:url];
UIImage*image=[UIImage imageWithData:data];
//回到主线程
[[NSOperationQueue mainQueue]addOperationWithBlock:^
{
// cell.imageView.image=image;
if (image)
{
_image[urlString]=image;
}
[_operations removeObjectForKey:urlString];
[_tbView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}];
}];
[_opaque addOperation:operation];
[_operations setValue:operation forKey:urlString];
}
3.********************
/**
* 当用户拖拽表格时
*
* @param scrollView <#scrollView description#>
*/
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//暂停下载
[_opaque setSuspended:YES];
}
/**
* 停止拖拽
*
* @param scrollView <#scrollView description#>
*/
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[_opaque setSuspended:NO];
}
4.******************************
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
//移除所有的下载
[_opaque cancelAllOperations];
[_operations removeAllObjects];
[_image removeAllObjects];
}
如何是cell中的图片只下载一次
最新推荐文章于 2022-03-01 10:44:38 发布