我需要從網頁/文件加載一些UIImages。我在尋找,我在其他question發現這個代碼:UITableViewCell加載圖像和重用單元格
if (![[NSFileManager defaultManager] fileExistsAtPath:user.image]) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSData *imageData =[NSData dataWithContentsOfURL:[NSURL URLWithString:user.imageURL]];
[imageData writeToFile:user.image atomically:YES];
dispatch_sync(dispatch_get_main_queue(), ^{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIImage *image = [UIImage imageWithData:imageData];
[self.imageFriends setObject:image forKey:[NSNumber numberWithInt:user.userId]];
cell.imageView.image = image;
[cell setNeedsLayout];
NSLog(@"Download %@",user.image);
});
});
cell.imageView.image=[UIImage imageNamed:@"xger86x.jpg"];
} else {
NSLog(@"cache");
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image = [UIImage imageWithContentsOfFile:user.image];
//[self.imageFriends setObject:image forKey:[NSNumber numberWithInt:user.userId]];
dispatch_sync(dispatch_get_main_queue(), ^{
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
newCell.imageView.image=image;
[newCell setNeedsLayout];
});
});
}
但問題是,當我快速滾動到頂部或底部的圖像加載錯誤,有一個短暫的延遲何時結束。
所以問題是......我如何在正確的單元格中加載UIImages,當我使用隊列來獲取它們時?謝謝!
關於UIImage不是線程安全的說明是我試圖解決的問題的關鍵。 – JamesSwift 2013-12-10 03:04:10