2013-03-07 49 views
2

我加載圖像到的tableView,每次函數如何做到多線程將圖像加載到tableView更快?

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

被執行時,圖像的不同的URL會..

我的問題是其採取了這麼多時間來加載圖像..

我的代碼..

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    self.tableView1 = tableView; 
    static NSString *simpleTableIdentifier = @"SimpleTableCell"; 
    SimpleTableCell *cell = (SimpleTableCell *)[tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
if (cell == nil) 
{ 
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil]; 
    cell = [nib objectAtIndex:0]; 
} 

    cell.nameLabel.text = title; 

    NSString *imageURL = [NSString stringWithFormat: @"http://www.xyz.com/image1.png]; 

    cell.thumbnailImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:fullURL]]]; 
} 
return cell; 
} 

每次圖像URL會改變,這將需要時間來加載每個圖像..

任何人都可以提出任何想法來解決這個問題? 多線程如何使用此代碼? 哪裏,我應該在代碼中編輯?

+1

https://github.com/rs/SDWebImage – janusbalatbat 2013-03-07 11:51:30

回答

3

您必須下載圖像背景,如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *simpleTableIdentifier = @"SimpleTableCell"; 
    SimpleTableCell *cell = (SimpleTableCell *)[tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
     dispatch_async(queue, ^{ 

      NSString *u=[NSString stringWithContentsOfFile:r.url encoding:NSUTF8StringEncoding error:nil]; 
      NSURL *imageURL=[NSURL URLWithString:u]; 
      NSData *imageData=[NSData dataWithContentsOfURL:imageURL]; 
      dispatch_sync(dispatch_get_main_queue(), ^{ 
       SimpleTableCell *cell = (SimpleTableCell *)[tableView cellForRowAtIndexPath:indexPath]; 
       cell.thumbnailImageView.image=[UIImage imageWithData:imageData]; 
       [cell setNeedsLayout]; 

      }); 
     }); 

    } 

    return cell; 
} 

與所需的編輯本應該爲你工作,你的表視圖方法只需使用上面的代碼。

+0

您好感謝..我想知道什麼是r.url是這裏..和IM不從任何文件加載URL ..這些網址r動態和即時訪問它從網.. – Raju 2013-03-07 12:19:14

+0

@Raju:其實在我的應用程序中,我顯示的單元格中的網址。你不需要這樣做。我編輯了我的答案。它是否適用於圖像? – 2013-03-07 12:30:44

+0

謝謝我得到了解決方案。 – Raju 2013-03-07 12:47:32

0

傑里米的答案另一種我以前使用的是HJCache框架

可以只使用HJManagedImage對象,它會下載並異步緩存圖片爲您