2012-02-17 44 views
1

我已經看到了一些文章,建議在塊中使用類似下面的內容來異步下載圖像,以便調用setNeedsDisplay主線程並讓它顯示得更快。cellForRowAtIndexPath:setNeedsDisplay不適用於在後臺下載的圖像,即使在主線程中調用它時也是如此

dispatch_async(main_queue, ^{ 
       [view setNeedsDisplay]; 
      }); 

我想這是可以看到下面,但沒有被當他們被下載顯示的圖像。一般大約有4-5秒的延遲。我知道這一點,因爲如果我選擇任何特定的行,圖像出現,而其他人仍然不顯示。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    UIImageView *iv = (UIImageView*)[cell viewWithTag:kCellSubViewWavImageView];; 

     //async for scroll performance 
     dispatch_queue_t queue = 
     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
     dispatch_async(queue, ^{ 

      NSURL *url = [[NSURL alloc] initWithString:[self.user.favWavformURLAr objectAtIndex:indexPath.row]]; 
      NSLog(@"background"); 
      NSData *imageData = [[NSData alloc] initWithContentsOfURL:url]; 
      UIImage *image = [[UIImage alloc] initWithData:imageData]; 

      iv.image = image; 

      dispatch_queue_t main_queue = dispatch_get_main_queue(); 
      dispatch_async(main_queue, ^{ 
       NSLog(@"main thread"); 
       [iv setNeedsDisplay]; 
      }); 

     }); 

    } 

    return cell; 
} 

順便說一句,NSLog(@"background");NSLog(@"main thread");調用下面按以下順序呼叫初始6個細胞,而這正是我所期望的印刷,我想。但仍然不起作用:

2012-02-17 20:46:27.120 SoundcloudFavs[8836:1c03] background 
2012-02-17 20:46:27.169 SoundcloudFavs[8836:1b03] background 
2012-02-17 20:46:27.170 SoundcloudFavs[8836:6b07] background 
2012-02-17 20:46:27.173 SoundcloudFavs[8836:7503] background 
2012-02-17 20:46:27.174 SoundcloudFavs[8836:7103] background 
2012-02-17 20:46:27.177 SoundcloudFavs[8836:8003] background 
2012-02-17 20:46:27.219 SoundcloudFavs[8836:207] main thread 
2012-02-17 20:46:27.270 SoundcloudFavs[8836:207] main thread 
2012-02-17 20:46:27.282 SoundcloudFavs[8836:207] main thread 
2012-02-17 20:46:27.285 SoundcloudFavs[8836:207] main thread 
2012-02-17 20:46:27.296 SoundcloudFavs[8836:207] main thread 
2012-02-17 20:46:27.300 SoundcloudFavs[8836:207] main thread 

任何想法?

回答

3

嘗試在主線程中設置下載的圖像。

dispatch_async(main_queue, ^{ 
      NSLog(@"main thread"); 
      iv.image = image; 
     }); 

而且最好是作爲細胞,但cell.contentView子視圖不添加圖像。

+0

非常感謝你...這工作!不能相信我沒有想到它。 – Remover 2012-02-17 23:48:48

相關問題