2

我使用此代碼下載圖片:AFNetworking內存不足的問題

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    SECustomCollectionViewCell *collectionViewCell = (SECustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"SECustomCollectionViewCell" forIndexPath:indexPath]; 

    NSDictionary *artwork = [self.artworks objectAtIndex:indexPath.item]; 

    collectionViewCell.theImageView.image = nil; 

    if (artwork[@"video_url"]) 
    { 
     UIWebView *webView = (UIWebView *)[collectionViewCell.contentView viewWithTag:100]; 
     NSString * html = [self embedYouTube:artwork[@"video_url"] frame:collectionViewCell.frame]; 

     [webView setHidden:NO]; 

     [webView loadHTMLString:html baseURL:nil]; 

     [collectionViewCell.activityIndicator setHidden:YES]; 
    } 
    else 
    { 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:artwork[@"image_url"]]]; 

     UIImage *cachedImage = [[[UIImageView class] sharedImageCache] cachedImageForRequest:request]; 

     if (cachedImage) 
     { 
      collectionViewCell.theImageView.image = [UIImage scaleImage:cachedImage toWidth:collectionViewCell.frame.size.width]; 
      [collectionViewCell.activityIndicator setHidden:YES]; 
     } 
     else 
     { 
      [collectionViewCell.theImageView setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { 

       // Only update visible cell, to avoid inserting image to another cell. 
       SECustomCollectionViewCell *visibleCollectionViewCell = (id)[collectionView cellForItemAtIndexPath:indexPath]; 

       if (visibleCollectionViewCell) 
       { 
        [visibleCollectionViewCell.theImageView setImage:[UIImage scaleImage:image toWidth:collectionViewCell.frame.size.width]]; 

        [visibleCollectionViewCell.activityIndicator stopAnimating]; 

        [visibleCollectionViewCell.activityIndicator setHidden:YES]; 
       } 

      } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { 

      }]; 
     } 
    } 

    return collectionViewCell; 
} 

,但它會導致內存不足的問題。

+0

文件有多大?相當大的文件最好通過直接流式傳輸到文件下載。主線程上有很多計算,包括圖像縮放。 – zaph

+0

@Zaph我在服務器上有jpg文件,這是1.4MB,但XCode說tahat有70MB後加載到imageview –

+0

因此它不是AFNetworking,但造成內存使用的圖像代碼。形象有多大? JPEG或PNG等壓縮圖像,但是當創建圖像時,每個像素將有4個字節。正在進行的縮放也將使用內存。你應該在縮放方法周圍放置autorelease池,以便儘早釋放內存。 – zaph

回答

2

這不是AFNetworking,而是導致內存使用的圖像代碼。 JPEG壓縮圖像,但是當創建圖像時,每個像素將有4個字節。由於服務器上的所有AFNetworking 1.4MB的jpeg文件將加載。

看來你正在使用一些助手類看看該代碼和NSLog AFNetworking下載的實際數據的大小。

每個像素4個字節的5407×3605圖像將創建超過77MB的圖像。您可以對其進行縮放,但首先渲染原始圖像,縮放將使用更多內存,因爲最終您將獲得兩張圖像。

您需要將原始圖像和縮放比例的創建包裝到自動釋放池中,以便儘快釋放原始圖像。

最好不要在第一個地方加載如此大的圖像。