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;
}
,但它會導致內存不足的問題。
文件有多大?相當大的文件最好通過直接流式傳輸到文件下載。主線程上有很多計算,包括圖像縮放。 – zaph
@Zaph我在服務器上有jpg文件,這是1.4MB,但XCode說tahat有70MB後加載到imageview –
因此它不是AFNetworking,但造成內存使用的圖像代碼。形象有多大? JPEG或PNG等壓縮圖像,但是當創建圖像時,每個像素將有4個字節。正在進行的縮放也將使用內存。你應該在縮放方法周圍放置autorelease池,以便儘早釋放內存。 – zaph