2011-11-21 75 views
2

所以我正在開發包含有在細胞圖像表格視圖的應用程序。我從URL下載所有這些圖像並將它們存儲在一個數組中。我需要異步加載這些圖像,所以我決定使用NSURLConnectionDataDelegate。我試過這個代碼:獲取圖像異步

- (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]; 
    } 

    NSUInteger row = [indexPath row]; 
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[URLsArray objectAtIndex:row]]]; 
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
    if (theConnection) { 
     receicedData = [[NSMutableData alloc] init]; 
    } else { 
     NSLog(@"Failed."); 
    } 
    return cell; 
} 

但它不起作用。並且我不知道該寫什麼:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 

將圖像設置爲單元格中的圖像視圖。誰能幫忙?

回答

6

我會強烈建議使用AFNetworking,只是因爲它需要照顧這些種類的擔憂。

最起碼,看看他們的UIImageView category,因爲它可以讓你做到這一點:

UIImageView *imgView = //alloc, get it from a nib, whatever; 
[imgView setImageWithURL:[NSURL URLWithString:@"StringPath"]]; 
+0

但是,如果使用setImageWithURL,它會同步加載圖片,不是嗎?如果是,如何使它異步? – Noobass

+1

如果按照文檔的鏈接,你會看到,它明確指出,圖像將異步下載。 – javieralog

+0

好的,但有什麼辦法沒有使用任何額外的庫? – Noobass

0

對於一個簡單的解決方案,我會建議使用Cached Image for iOS。這是一段簡單的代碼,您可以將其添加到xcode項目中,並且它可以滿足您的需求(+支持緩存)。