Tôi đã tìm kiếm một cách cắt rõ ràng để làm điều này và đã không tìm thấy bất cứ nơi nào mà sẽ đưa ra một ví dụ và giải thích nó rất tốt. Tôi hi vọng bạn có thể giúp tôi vượt qua.Cách thích hợp để sử dụng NSCache với dispatch_async trong ô bảng tái sử dụng là gì?
Đây là mã của tôi mà tôi đang sử dụng:
lợi nhuận- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"NewsCell";
NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
NewsItem *item = [newsItemsArray objectAtIndex:indexPath.row];
cell.newsTitle.text = item.title;
NSCache *cache = [_cachedImages objectAtIndex:indexPath.row];
[cache setName:@"image"];
[cache setCountLimit:50];
UIImage *currentImage = [cache objectForKey:@"image"];
if (currentImage) {
NSLog(@"Cached Image Found");
cell.imageView.image = currentImage;
}else {
NSLog(@"No Cached Image");
cell.newsImage.image = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void)
{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:item.image]];
dispatch_async(dispatch_get_main_queue(), ^(void)
{
cell.newsImage.image = [UIImage imageWithData:imageData];
[cache setValue:[UIImage imageWithData:imageData] forKey:@"image"];
NSLog(@"Record String = %@",[cache objectForKey:@"image"]);
});
});
}
return cell;
}
Cache Nil cho tôi.
Bạn có thể muốn xem dự án SDWebImage, điều này đã tìm ra tất cả. –
Bạn có thể cung cấp liên kết không? – mcphersonjr
https://github.com/rs/SDWebImage – Rob