GCD UITableViewasynchronous加载图像,加载错误的单元格直到新图像下载

我有一个UITableView与自定义单元格。 我使用Grand Central Dispatchasynchronous加载图像。 一切工作正常,但是当我向下滚动,以前加载的图像显示,直到新的图像下载。 这是我的代码:

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"]]; } 

任何build议感激。 PS我重用这些单元格

捕获单元格,而不是捕获索引path,然后使用以下命令获取单元格:

 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

这样,如果单元格现在不在屏幕上,您将返回零,图像将不会设置在错误的单元格上。

dispatch_async()之后需要添加的另一件事是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"]]; } 

在你的- (void)tableView:(UITableView *)aTableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {你需要清除图像,或重置它到你的微调。 由于表视图行被重用,这就是您将看到的行为。

不是UITableViewCell定义 – (无效)prepareForReuse为此目的? 覆盖它并清除你的imageView。