自定义UITableViewCell - UIImageView的异步UIImage

时间:2011-12-01 10:55:48

标签: ios uiimageview uitableview asihttprequest

我创建了一个自定义的UITableViewCell,它由2个UILabel和一个UIImageView组成。

与单元格关联的数据可通过名为CellInfo的NSObject类获得。 CellInfo有2个NSString类型的属性和一个UIImage属性。

当我在initWithData方法(CellInfo类)中创建一个CellInfo实例时,我会执行以下操作:

if(self = [super alloc])
{
  //initialize strings variables
  self.name = aName;
  self.descritpion = aDescription;
  [self grabImage]    
}
return self;

其中grabImage(在CellInfo类中)使用ASIHTTPrequest框架以异步方式获取图像(在下面的代码中NSURL是相同但实际上它随数据而变化)

- (void)grabImage
{
   NSURL *url = [NSURL URLWithString:@"http://myurl.com/img.png"];
   __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

   [request setCompletionBlock:^{               

      NSData *data = [request responseData];
      UIImage* img = [[UIImage alloc] initWithData:data];

      self.image = img;
      [img release];

      // Send a notification if image has been downloaded
      [[NSNotificationCenter defaultCenter] postNotificationName:@"imageupdated" object:self];
   }];
   [request setFailedBlock:^{
      NSError *error = [request error];
     // Set default image to self.image property of CellInfo class
   }];
   [request startAsynchronous];
}

我还有一个UITableViewController,可以将数据加载到自定义单元格中,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    // Do stuff here...

    // Configure the cell...
    ((CustomTableViewCell*)cell).nameOutlet.text = ((CellInfo*) [self.infoArray objectAtIndex:indexPath.row]).name;
    ((CustomTableViewCell*)cell).descriptionOutlet.text = ((CellInfo*) [self.infoArray objectAtIndex:indexPath.row]).descritpion;
    ((CustomTableViewCell*)cell).imageViewOutlet.image = ((CellInfo*) [self.infoArray objectAtIndex:indexPath.row]).image;

    return cell;
}

另外,这个UITableViewController会观察来自CellInfo类的通知,因为在启动时,不会显示可见单元格的图像。这是捕获通知时调用的方法:

- (void)imageUpdated:(NSNotification *)notif {

    CellInfo * cInfo = [notif object];
    int row = [self.infoArray indexOfObject:cInfo];
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row inSection:0];

    NSLog(@"Image for row %d updated!", row);

    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationNone];
}

代码效果很好,但我想知道我是做得对还是有更好的方法来做到这一点。 我怀疑如下:在每个CellInfo实例中保存下载的图像是正确的还是可以使用其他方法来缓存图像,例如使用ASIHTTPRequest提供的缓存策略?

P.S。如果已经下载了特定CellInfo实例的图像,则不会调用grabImage。

1 个答案:

答案 0 :(得分:0)

我相信这很漂亮。而不是你可以继承UIImageView类并创建一个像[AsyncUIImageView initWithURL:]这样的初始化器,然后将ASIHttpRequest逻辑放在视图中。

完成图片加载后,可能有两种方式:

  1. 可以调用[self setNeedsDisplay]UIView方法),以便重新绘制图像视图。

  2. 您可以将UITableViewCellUITableView作为delegate传递给AsyncUIImgeView,以便它可以告诉表格视图重新加载该单元格。

    < / LI>
相关问题