问题描述
我有一个UITableView与自定义单元格。我使用Grand Central Dispatch异步加载图像。一切工作正常,但当我向下滚动,以前加载的图像显示,直到新的图像下载。这是我的代码:
I have a UITableView with custom cells. I load images asynchronously using Grand Central Dispatch. Everything works fine, but when I scroll down, previously loaded images are shown till the new image is downloaded. Here is my code:
if (![[NSFileManager defaultManager] fileExistsAtPath:[path stringByAppendingPathComponent:@"image.png"]])
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSString *url=[pat stringByAppendingPathComponent:@"comments.txt"];
NSString *u=[NSString stringWithContentsOfFile:url encoding:NSUTF8StringEncoding error:nil];
NSURL *imageURL=[NSURL URLWithString:u];
NSData *image=[NSData dataWithContentsOfURL:imageURL];
[image writeToFile:[pat stringByAppendingPathComponent:@"image.png"] atomically:YES];
dispatch_sync(dispatch_get_main_queue(), ^{
cell.imageView.image=[UIImage imageWithContentsOfFile:[pat stringByAppendingPathComponent:@"image.png"]];
[cell setNeedsLayout];
NSLog(@"Download");
});
});
}
else
{
NSLog(@"cache");
cell.imageView.image=[UIImage imageWithContentsOfFile:[pat stringByAppendingPathComponent:@"image.png"]];
}
任何建议。
P.S.我重复使用单元格
Any suggestions appreciated.P.S. I reuse the cells
推荐答案
而不是捕获您需要捕获索引路径的单元格, / p>
Rather than capturing the cell you need to capture the index path, then get the cell back using:
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
这样,如果单元格现在离屏,你会得到零,
That way, if the cell is now off screen you'll get nil back and the image won't be set on the wrong cell.
在 dispatch_async()
之后,您需要添加的另一件事是 cell.imageView.image = somePlaceholderImage
。
The other thing you need to add after your dispatch_async()
is a cell.imageView.image=somePlaceholderImage
.
例如:
if (![[NSFileManager defaultManager] fileExistsAtPath:[path stringByAppendingPathComponent:@"image.png"]])
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSString *url=[pat stringByAppendingPathComponent:@"comments.txt"];
NSString *u=[NSString stringWithContentsOfFile:url encoding:NSUTF8StringEncoding error:nil];
NSURL *imageURL=[NSURL URLWithString:u];
NSData *image=[NSData dataWithContentsOfURL:imageURL];
[image writeToFile:[pat stringByAppendingPathComponent:@"image.png"] atomically:YES];
dispatch_sync(dispatch_get_main_queue(), ^{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.imageView.image=[UIImage imageWithContentsOfFile:[pat stringByAppendingPathComponent:@"image.png"]];
[cell setNeedsLayout];
NSLog(@"Download");
});
});
cell.imageView.image=[UIImage imageNamed:@"placeholder"];
}
else
{
NSLog(@"cache");
cell.imageView.image=[UIImage imageWithContentsOfFile:[pat stringByAppendingPathComponent:@"image.png"]];
}
这篇关于GCD UITableView异步加载图像,加载错误的单元格,直到新的图像下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!