使用AFNetworking下载时泄漏

时间:2014-12-06 00:28:22

标签: ios afnetworking

基本上,当文件下载完成后,会出现""#34;在内存中永远不会被释放。这是导致该问题的代码的简单示例,内存高达50mb左右,它只是坐在那里,永远不会被释放(见下面的截图)。知道发生了什么事吗?

-(void)download {
    NSString* urlString = @"http://download.thinkbroadband.com/50MB.zip";
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    AFHTTPRequestOperation* operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        NSLog(@"%lldmb of %lldmb downloaded", totalBytesRead / 1024 / 1024, totalBytesExpectedToRead / 1024 / 1024);
    }];

    [operation setCompletionBlockWithSuccess:^(__weak AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Download completed.");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error.localizedDescription);
    }];

    [operation start];
}

下载前:

enter image description here

下载后:

enter image description here

1 个答案:

答案 0 :(得分:2)

在我自己使用AFNetworking 2.5进行的iOS 8.1测试中,这似乎是在调试但不是发布模式的情况。鉴于您的代码不能正常工作,我做了以下测试用例:

- (IBAction)startDownload:(UIButton *)sender 
{
    NSString *downloadURLString = @"http://mirror.internode.on.net/pub/test/50meg.test";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:downloadURLString]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Download succeeded.");
        self.stateLabel.text = @"Download succeeded.";
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Download failed with error: %@", error);
        self.stateLabel.text = @"Download failed.";
    }];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        NSLog(@"Bytes read: %lu", bytesRead);
        NSLog(@"Total bytes read %lld", totalBytesRead);
        NSLog(@"Total progress: %Lf", (long double)totalBytesRead / totalBytesExpectedToRead);
        self.progressView.progress = (long double)totalBytesRead / totalBytesExpectedToRead;
    }];

    NSLog(@"Starting download.");
    NSOperationQueue *downloadQueue = [[NSOperationQueue alloc] init];
    [downloadQueue addOperation:operation];
}

使用此代码,一旦下载完成,在发布模式下,内存使用量将回退到预先下载级别。