UITableViewCell图片异步下载

1.具体步骤:
  
  首先在return cell的方法中,
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexP   ath
   {
      TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:inde          xPath];
      
       news *n = (news *)self.dataarr[indexPath.row];
  
      //加载图片
       if (nil == n.myImage && NO == n.isloading)
         {//临时占位符
            cell.myImage.image = [UIImage imageNamed:@"2.png"];
            //赶紧加载图片
             [n loadImage];
             //添加一个观察者
        [n addObserver:self forKeyPath:@"myImage" options:NSKeyValueObservingOptionNew context:(__bri       dge void *)(indexPath)];
         }
      else
        {
        //说明不需要在加载了
        cell.myImage.image = n.myImage;
        }
         
        return cell;
   }

   - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)chan     ge context:(void *)context
{
    //1.拿到新图片的数据
    UIImage *tempimage = change[NSKeyValueChangeOldKey];
    //判断这个值是不是为空
    if([tempimage isEqual:[NSNull null]])
    {
        return;
    }
    //拿到当前图片所在的indexpath
    NSIndexPath *indexpath = CFBridgingRelease(context);
    //拿到当前的显示的cell的indexpath
    NSArray *indexarray = [self.tableView indexPathsForVisibleRows];
    //判断indexpath是否正在显示
    if ([indexarray containsObject:indexpath])
    {//拿到cell
        TableViewCell *cell = (TableViewCell *)[self.tableView cellForRowAtIndexPath:indexpath];
        //换图
        cell.imageView.image = tempimage;
        //更新cell
        [self.tableView reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:(UITableViewRowAnimation        Automatic)];
    }
    [object removeObserver:self forKeyPath:@"myImage"];
}


你可能感兴趣的:(UITableViewCell图片异步下载)