2011-12-31 109 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百萬次下載),並對結果完全滿意。