【问题标题】:Receiving memory warning when downloading multiple files with AFNetworking使用 AFNetworking 下载多个文件时收到内存警告
【发布时间】:2013-10-02 14:03:04
【问题描述】:

我正在从 UIGridViewCells 下载电影文件。我的代码是:

NSMutableURLRequest* rq = [[APIClient sharedClient] requestWithMethod:@"GET" path:[[self item] downloadUrl] parameters:nil];
    [rq setTimeoutInterval:5000];
    _downloadOperation = [[AFHTTPRequestOperation alloc] initWithRequest:rq] ;
    _downloadOperation.outputStream = [NSOutputStream outputStreamToFileAtPath:[[self item] localUrl] append:NO];
    __weak typeof(self) weakSelf = self;
    [_downloadOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", [weakSelf.item localUrl]);
        [Helper saveItemDownloaded:weakSelf.item.productId];
        weakSelf.isDownloading = NO;
        [weakSelf.progressOverlayView removeFromSuperview];
        [weakSelf setUserInteractionEnabled:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        [weakSelf.progressOverlayView removeFromSuperview];
        [weakSelf setUserInteractionEnabled:YES];
        weakSelf.isDownloading = NO;
        }];
    [_downloadOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float progress = totalBytesRead / (float)totalBytesExpectedToRead;
        weakSelf.progressOverlayView.progress = progress;
    }];
    [[NSOperationQueue mainQueue] addOperation:_downloadOperation];

而ItemCell中的属性是:

@property (nonatomic, retain) AFHTTPRequestOperation *downloadOperation;

在 1-2 次成功下载 (20mb) 后,我收到内存警告。每次下载使用的内存都会增加,下载完成后不会减少。

来自仪器:

【问题讨论】:

  • 你是在for循环里面做这一切吗?
  • 对于下载操作,是的。但是我发送了一个播放电影的列表。

标签: ios memory-management afnetworking-2


【解决方案1】:

我相信使用 AFNetworking 下载文件的首选方法是设置“outputStream”属性。

根据 AFNetworking 文档:

用于写入接收到的数据直到请求完成的输出流。

默认情况下,数据会累积到缓冲区中,该缓冲区会在请求完成后存储到responseData。当设置outputStream 时,数据不会被累积到内部缓冲区中,因此,已完成请求的responseData 属性将为nil。设置后,输出流将在网络线程运行循环中调度。

我遇到了同样的问题,使用“outputStream”解决了。

【讨论】:

    【解决方案2】:

    对每个下载的文件使用@autorelease:

    for(File* file in fileList)
    {
        @autoreleasepool {
            [self downloadFile:file];
        } 
    }
    

    这将释放您下载的单独文件之间分配的所有变量和数据。

    您还应该追踪那些内存泄漏。我在仪器屏幕截图中看到了一些可见的内容。

    【讨论】:

    • 当我跟踪内存泄漏时,我看不到任何与我的代码相关的问题。我更新了我的问题,请检查。
    猜你喜欢
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 2013-03-03
    • 2014-12-18
    • 1970-01-01
    相关资源
    最近更新 更多