从url使用uitableview缓存UIImage

我有一个uitableview,自定义单元格包含两个UImage。 徽标图像来自在线网站,这就是为什么需要缓存图像。 直到现在加载图像是这样的:

NSURL * imageURL = [NSURL URLWithString:[arra1 objectAtIndex:indexPath.row / 2]]; NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; NSURL * imageURL2 = [NSURL URLWithString:[arra2 objectAtIndex:indexPath.row / 2]]; NSData * imageData2 = [NSData dataWithContentsOfURL:imageURL2]; cell.ima1.image = [UIImage imageWithData:imageData]; cell.ima2.image2 = [UIImage imageWithData:imageData2]; 

我从搜索中学到的是dataWithContentsOfURL不是异步的,滚动时需要花费很多时间。 我尝试了几种方法,但我似乎无法找到正确的方法。 这是我第一次缓存UIImages,我非常感谢对实现的详细解释,所以我可以学习除了完成工作。 非常感谢

我使用这个库是完美的

  • SDWebImage

您只需要#import 到您的项目,并且您只需使用以下代码下载图像时也可以定义占位符:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"MyIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; } // Here we use the new provided setImageWithURL: method to load the web image [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://sofzh.miximages.com/ios/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; cell.textLabel.text = @"My Text"; return cell; } 

它还可以缓存下载的图像并为您提供出色的性能。

希望它能帮到你!

在我看来, SDWebImage是最好的选择。

您只需将其包含在您的应用中并使用它:

  •  SDWebImageManager *manager = [SDWebImageManager sharedManager]; [manager downloadWithURL:[NSURL URLWithString:image_url] options:0 progress:nil completed:^(UIImage *images, NSError *error, SDImageCacheType cacheType, BOOL complete) { myImageView.image = images; }] ; 

它以异步方式下载图像,因此不会阻止UI。

您可以查看这些示例应用程序

  1. LazyTableImages – 来自Apple的示例应用程序
  2. MonoTouch中,LazyTableImages
  3. robertmryan- LazyTableImages – 清楚地解释了苹果样本应用程序的局限性。

希望这可以帮助。

Checkout UIImageLoader https://github.com/gngrwzrd/UIImageLoader

易于加载图像,您可以获得要处理的所有场景的回调:

 NSURL * imageURL = myURL; [[UIImageLoader defaultLoader] loadImageWithURL:imageURL \ hasCache:^(UIImage *image, UIImageLoadSource loadedFromSource) { //there was a cached image available. use that. self.imageView.image = image; } sendRequest:^(BOOL didHaveCachedImage) { //a request is being made for the image. if(!didHaveCachedImage) { //there was not a cached image available, set a placeholder or do nothing. self.loader.hidden = FALSE; [self.loader startAnimating]; self.imageView.image = [UIImage imageNamed:@"placeholder"]; } } requestCompleted:^(NSError *error, UIImage *image, UIImageLoadSource loadedFromSource) { //network request finished. [self.loader stopAnimating]; self.loader.hidden = TRUE; if(loadedFromSource == UIImageLoadSourceNetworkToDisk) { //the image was downloaded and saved to disk. //since it was downloaded it has been updated since //last cached version, or is brand new self.imageView.image = image; } }];