我有一個UITableView自定義單元格。我使用Grand Central Dispatch異步加載圖像。一切工作正常,但當我向下滾動,以前加載的圖像顯示,直到新的圖像下載。這裏是我的代碼:GCD UITableView異步加載圖像,加載錯誤的單元格,直到新圖像下載
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.我重用這些單元格
感謝您的回覆......但是,請您提供一些示例代碼? – blackhawk4152
更新了我的答案 – hypercrypt
謝謝,男人!正是我想要的 – blackhawk4152