在tableviewcontroller中caching图像

我想将图像保存到TableViewcontroller的caching中。 我写了下面的代码,但cacheImage总是为零。

@property (nonatomic,strong)NSCache *imageCache; @synthesize imageCache; - (void)viewDidLoad { [super viewDidLoad]; self.imageCache = [[NSCache alloc] init]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; cell.textLabel.text = [[tableData objectAtIndex:indexPath.row] valueForKey:@"name"]; cell.textLabel.font = [UIFont fontWithName:@"BebasNeue" size:24]; cell.textLabel.textColor = [UIColor whiteColor]; UIImage *cachedImage = [imageCache objectForKey:@"indexObject"]; if (cachedImage) { dispatch_async(dispatch_get_main_queue(), ^{ cell.imageView.image = cachedImage; }); } else { NSString *imageURLString=[[tableData objectAtIndex:indexPath.row] valueForKey:@"picture"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSURL *url = [NSURL URLWithString:imageURLString]; NSData *data = [[NSData alloc] initWithContentsOfURL:url]; UIImage *tmpImage = [[UIImage alloc] initWithData:data]; dispatch_async(dispatch_get_main_queue(), ^{ UITableViewCell *newsCell = [self.grillMenuTable cellForRowAtIndexPath:indexPath]; [imageCache setObject:tmpImage forKey:@"indexObject"]; if (newsCell) { newsCell.imageView.image=tmpImage; [newsCell setNeedsLayout]; } }); }); } return cell; } 

乔使用下面的代码build议,但仍然cell.imageview.image总是零。

  NSString *imageURLString=[[tableData objectAtIndex:indexPath.row] valueForKey:@"picture"]; [[DLImageLoader sharedInstance] loadImageFromUrl:imageURLString completed:^(NSError *error, UIImage *imgData) { cell.imageView.image = imgData; }]; 

不要试图重新发明轮子。 你应该使用外部库来做到这一点,有一些很好的例子。 看看SDWebImage ,它确实是你想要的。

使用它,你可以忘记队列,手动caching…只需导入标题:

 #import <SDWebImage/UIImageView+WebCache.h> 

在你的tableView:cellForRowAtIndexPath:方法中,你可以使用库提供的setImageWithURL:或其任何变体:带有占位符等)方法将图像设置为UIImageView

 NSString* imageURL = [[tableData objectAtIndex:indexPath.row] valueForKey:@"picture"]; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURL]]; 

就这样。 图书馆照顾你的一切。 如果你想以某种方式pipe理后面的caching并对其进行configuration,可以使用SDWebImageManager类(更多信息在GitHub页面中)。