我一直在寻找一种明确的方法来做到这一点,但还没有找到任何可以举例说明并很好解释的地方。我希望你能帮助我。
这是我正在使用的代码:
- (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;
}
缓存为我返回 nil。