2011-12-31 105 views
0

我有一个包含4张照片,我从网络中这些照片,但问题是,当我向下滚动,这些照片被再次下载 enter image description here如何下载照片?

中的UITableView这是代码一个UITableViewCell:

 ITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellPhoto"]; 

if (cell == nil) { 

    NSArray *nibObject = [[NSBundle mainBundle] loadNibNamed:@"CustomCellThumbnails" owner:self options:nil]; 
    cell = [nibObject objectAtIndex:0]; 
} 

// Get the photos 
int getPhotos = indexPath.row * 4; 

for (int i = 1; i <= 4; i++) { 

    if (getPhotos < [imageArray count]) 
    { 
     UIButton *imageButton = (UIButton*)[cell viewWithTag:i]; 
     NSString *url = [imageArray objectAtIndex:getPhotos]; 

     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
      NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.siteweb.com%@",url]]]; 
      UIImage *imageFieldProfile = [[UIImage alloc] initWithData:imageData]; 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       // Set the phoyo to the UIButton 
       [imageButton setBackgroundImage:imageFieldProfile forState:UIControlStateNormal]; 
       [imageFieldProfile release]; 
       // Set the corner of UIButton 
       [imageButton.layer setCornerRadius:5.0]; 
       [imageButton.layer setMasksToBounds:YES]; 
       imageButton.tag = getPhotos; 
      }); 
     }); 

     [imageButton addTarget:self action:@selector(displayPhoto:) forControlEvents:UIControlEventTouchUpInside]; 

    }   
    getPhotos ++; 
} 

回答

1

您应该使用视图控制器来填充单元格,而不是UITableViewCell。如果你这样做,这不仅是一种更好的编码风格,保存数据也更容易。

无论如何,如果你真的必须:用某种存储表的​​初始化的UITableViewCell,这样就可以存储你所下载的数据:重写initWithStyle:reuseIdentifier:initWithStyle:reuseIdentifier:usingCacheTable:

但是,再次,要做到这一点,正确的做法是在视图控制器中加载数据,并让UIView子类只显示内容。

+0

但是,如果我有一个自定义的UITableViewCell在笔尖文件如何创建与initWithStyle一个UITableViewCell:reuseIdentifier:usingCacheTable: – 2011-12-31 20:09:23

+0

不知道 - 考虑将其添加为一个属性,使用'[细胞setMyCache:]'代替。 – 2011-12-31 20:11:28

0

您应该将图像保存或缓存在下载的其他对象中,而不是在表格视图单元格中。也许使用表视图单元格从中请求图像的某种数据源或模型对象,而不是让表视图单元格直接发出任何URL请求。然后模型对象可以在下载之后并将它们交给单元之前缓存图像。

0

您可以将延迟加载图像视图与本地缓存结合使用。使用ASIHTTPRequest和正确设置缓存标志相结合可以很容易地实现。

ASIHTTPRequest非常易于使用,它的缓存控制非常好。

与其他解决方案相反,我会坚持使用UITableView及其UITableViewCells,因为这样您可以使用de/queued单元,而无需自己构建此类逻辑。

我已将这样的解决方案用于主要的newsmagazine应用程序(超过2百万次下载),并对结果完全满意。