2013-03-30 36 views
0

我有一張小圖片的表格。它是如何工作的: 我有一個模型,它接受來自Instagram的JSON響應並將其全部放入字典數組中。 在我的方法cellForRowAtIndexPath我設置單元格的標記爲indexpath.row,然後開始下載圖像(從模型獲取url)通過使用dispatch_async。 圖像加載完成後,我有一個檢查來比較當前單元格和當前indexpath.row的標記,如果它們相同,則繪製圖像。 它工作正常,直到我刷新我的模型。簡單地重新載入相同的數據會導致表格上出現奇怪的行爲 - 它將前三個單元顯示爲相同的圖像。 我該如何解決這個問題?更新UITableView - 錯誤的單元格和相同的圖像

這裏是我的細胞的方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    cell.tag = indexPath.row; 

    if (self.loader.parsedData[indexPath.row] != nil) 
    { 
     cell.imageView.image = nil; 

     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
      dispatch_async(queue, ^(void) { 

       NSString *url = [self.loader.parsedData[indexPath.row] objectForKey:@"imageLR"]; 

       if ([self.cache objectForKey:url] != nil) 
       { 
        NSData *imageData = [self.cache objectForKey:url]; 
        self.tempImage = [[UIImage alloc] initWithData:imageData]; 
       } 

       else 
       { 

       NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]; 
       self.tempImage = [[UIImage alloc] initWithData:imageData]; 
       [self.cache setObject:imageData forKey:[self.loader.parsedData[indexPath.row] objectForKey:@"imageLR"]]; 

       } 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        if (cell.tag == indexPath.row) 
        { 
         cell.imageView.image = self.tempImage; 
         [cell setNeedsLayout]; 
        } 

        }); 
      }); 

    cell.textLabel.text = [self.loader.parsedData[indexPath.row] objectForKey:@"id"]; 
    } 

    return cell; 
} 

我試圖把[實現代碼如下reloadData]無處不在,但它並不能幫助。

回答

0

我發現了一個問題。 我已經使用tableViewController屬性來保存下載的數據。 因此,在任何時候,各個塊可以同時寫入,並使用該指針來設置圖像。 更新發生了什麼,幾個塊同時使用它,導致相同的圖像。 我已經切換到使用本地NSData變量,它現在很好用。

相關問題