ios - 使用 AFNetworking NSOperations 连续下载大量文件......内存不足

标签 ios objective-c multithreading automatic-ref-counting out-of-memory

注意:我使用的是 ARC。

我有一些代码向 http 服务器发出 1 个文件列表请求(通过 JSON)。然后将该列表解析为模型对象,用于将下载操作(用于下载该文件)添加到不同的 nsoperationqueue,然后一旦完成添加所有这些操作(队列开始暂停),它就会启动队列并等待在继续之前完成所有操作。 (注意:这一切都是在后台线程上完成的,以免阻塞主线程)。

基本代码如下:

NSURLRequest* request = [NSURLRequest requestWithURL:parseServiceUrl];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    //NSLog(@"JSON: %@", responseObject);

    // Parse JSON into model objects

    NSNumber* results = [responseObject objectForKey:@"results"];
    if ([results intValue] > 0)
    {
        dispatch_async(_processQueue, ^{

            _totalFiles = [results intValue];
            _timestamp = [responseObject objectForKey:@"timestamp"];
            NSArray* files = [responseObject objectForKey:@"files"];

            for (NSDictionary* fileDict in files)
            {
                DownloadableFile* file = [[DownloadableFile alloc] init];
                file.file_id = [fileDict objectForKey:@"file_id"];
                file.file_location = [fileDict objectForKey:@"file_location"];
                file.timestamp = [fileDict objectForKey:@"timestamp"];
                file.orderInQueue = [files indexOfObject:fileDict];

                NSNumber* action = [fileDict objectForKey:@"action"];
                if ([action intValue] >= 1)
                {
                    if ([file.file_location.lastPathComponent.pathExtension isEqualToString:@""])
                    {
                        continue;
                    }

                    [self downloadSingleFile:file];
                }
                else // action == 0 so DELETE file if it exists
                {
                    if ([[NSFileManager defaultManager] fileExistsAtPath:file.localPath])
                    {
                        NSError* error;
                        [[NSFileManager defaultManager] removeItemAtPath:file.localPath error:&error];
                        if (error)
                        {
                            NSLog(@"Error deleting file after given an Action of 0: %@: %@", file.file_location, error);
                        }
                    }
                }

                [self updateProgress:[files indexOfObject:fileDict] withTotal:[files count]];

            }

            dispatch_sync(dispatch_get_main_queue(), ^{
                [_label setText:@"Syncing Files..."];
            });

            [_dlQueue setSuspended:NO];
            [_dlQueue waitUntilAllOperationsAreFinished];

            [SettingsManager sharedInstance].timestamp = _timestamp;

            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil);
            });
        });
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            callback(nil);
        });
    }


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
    callback(error);
}];

[_parseQueue addOperation:op];

然后是 downloadSingleFile 方法:

- (void)downloadSingleFile:(DownloadableFile*)dfile
{
NSURLRequest* req = [NSURLRequest requestWithURL:dfile.downloadUrl];

AFHTTPRequestOperation* reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:req];
reqOper.responseSerializer = [AFHTTPResponseSerializer serializer];

[reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation* op, id response)
 {
         __weak NSData* fileData = response;
         NSError* error;

         __weak DownloadableFile* file = dfile;

         NSString* fullPath = [file.localPath substringToIndex:[file.localPath rangeOfString:file.localPath.lastPathComponent options:NSBackwardsSearch].location];
         [[NSFileManager defaultManager] createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:Nil error:&error];
         if (error)
         {
             NSLog(@"Error creating directory path: %@: %@", fullPath, error);
         }
         else
         {
             error = nil;
             [fileData writeToFile:file.localPath options:NSDataWritingFileProtectionComplete error:&error];
             if (error)
             {
                 NSLog(@"Error writing fileData for file: %@: %@", file.file_location, error);
             }
         }

         [self updateProgress:file.orderInQueue withTotal:_totalFiles];
 }
                               failure:^(AFHTTPRequestOperation* op, NSError* error)
 {
     [self updateProgress:dfile.orderInQueue withTotal:_totalFiles];
     NSLog(@"Error downloading %@: %@", dfile.downloadUrl, error.localizedDescription);
 }];

[_dlQueue addOperation:reqOper];
}

我看到的是随着更多文件的下载,内存不断增加。这就像 responseObject 甚至整个 completionBlock 都没有被释放。

我试过使 responseObject 和 fileData 都变弱。我试过添加一个 autoreleasepool,我也试过使实际的文件域对象 __weak 但内存仍然攀升和攀升。

我已经运行了 Instruments 并且没有看到任何泄漏,但是它永远不会达到所有文件都已下载的程度,然后它会出现内存不足并出现严重的“无法分配区域”错误。查看分配,我看到一堆 connection:didFinishLoading 和 connection:didReceiveData 方法似乎永远不会被放弃,但是。不过,我似乎无法对其进行进一步调试。

我的问题:为什么内存不足?什么没有被释放,我怎样才能让它这样做?

最佳答案

这里发生了一些事情。最大的问题是您正在下载整个文件,将其存储在内存中,然后在下载完成后将其写入磁盘。即使只有一个 500 MB 的文件,您也会耗尽内存。

执行此操作的正确方法是使用具有异步下载功能的 NSOutputStream。关键是数据一到就写出来。它应该看起来像这样:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.outputStream write:[data bytes] maxLength:[data length]];
}

另外请注意,您是在 block 内部而不是外部创建弱引用。因此,您仍在创建一个保留循环和泄漏内存。当您创建弱引用时,它应该看起来像这样。

NSOperation *op = [[NSOperation alloc] init];
__weak NSOperation *weakOp = op;
op.completion = ^{
    // Use only weakOp within this block
};

最后,您的代码正在使用 @autoreleasepool。 NSAutoreleasePool 和 ARC 等价物 @autoreleasepool 仅在非常有限的情况下有用。作为一般规则,如果您不确定自己是否需要,则不需要。

关于ios - 使用 AFNetworking NSOperations 连续下载大量文件......内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19460435/

相关文章:

iphone - 在按钮事件中显示下拉项的代码如何?

ios - 如何在 IOS 7 中实现 UIViewController 与前后过渡的导航?

ios - 如何在没有 segue 的情况下使用通知中心将数据从第一个 TableView 发送到第二个 TableView

android - Flutter-使用 Android XML 作为 Widget

iOS : Custom UISegmentedControl does not adjust when orientation is changed

c++ - 多线程进程中同步写入日志

java - 简单的Java并发线程——捕获开始和结束

java - 在Spring MVC中,Controller是单例的,为什么我的代码是线程安全的?(Autowired HttpServeltRequest)

ios - UITableViewRowAction - 一个的背景颜色会影响另一个

objective-c - 这个: _Pragma ("clang assume_nonnull begin")是什么意思