【问题标题】:Using AFNetworking NSOperations to download a number of files serially.....runs out of memory使用 AFNetworking NSOperations 串行下载多个文件.....内存不足
【发布时间】:2013-10-18 23:15:57
【问题描述】:

注意:我使用的是 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 设为 __weak。我已经尝试添加一个自动释放池,并且我也尝试过使实际的文件域对象 __weak 但内存仍在不断攀升。

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

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

【问题讨论】:

  • 推特上有人提到 self 被保留是因为我正在使用 [self updateProgress] 所以它将控制器保留在完成块内,该完成块由操作所拥有的操作所拥有由控制器.....所以有保留周期。我将不得不看看当我将 [self updateProgress] 代码直接移动到块中时会发生什么。
  • 请注意,删除 [self updateProgress] 也没有解决问题

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


【解决方案1】:

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

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

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

另外值得注意的是,您是在块内部而不是外部创建弱引用。因此,您仍在创建保留周期并泄漏内存。当您创建弱引用时,它应该如下所示。

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

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

【讨论】:

  • 三个最佳实践建议的好答案!
  • 谢谢。我知道使用 NSOutputstream,但出于安全原因,我需要使用文件保护将数据写入磁盘。
  • 此外,代码中的 __weak 和 autoreleasepool 区域是我尝试查看是否使某些东西变弱有什么不同,或者 autoreleasepool 是否有任何不同以获得保留的任何内容的区域。 ..发布。但是,任何组合都不起作用,包括您在此处建议的方式。
  • “它不起作用”对诊断没有帮助。你所期待的发生或没有发生什么?如果我们没有足够的信息,我们将无能为力。
  • 没有发生的是问题没有解决。内存一直在上升,没有释放。我在这里发布的代码是在使用 __weak 和 autoreleasepool 修改了一堆地方之后。我可能应该把它恢复到我开始试验之前的样子。此外,当我在完成块之外创建 __weak 引用时,它们在执行块时已经被释放......所以它们没用
【解决方案2】:

在朋友的帮助下,我能够找出问题所在。

问题其实出在第一段代码中:

[_dlQueue waitUntilAllOperationsAreFinished];

显然,等待所有操作完成意味着这些操作也不会被释放。

与此相反,我最终向队列中添加了一个最终操作,该操作将执行最终处理和回调,并且内存现在更加稳定。

[_dlQueue addOperationWithBlock:^{
                    [SettingsManager sharedInstance].timestamp = _timestamp;

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

【讨论】:

    【解决方案3】:

    您正在下载什么样的文件?如果您正在使用图像或视频,则需要清除 URLCache,因为当您完成加载图像时,它会在缓存中创建 CFDATA 和一些信息,并且不会清除。当您的单个文件下载完成时,您需要明确清除它。它也永远不会被视为泄漏。

    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
        [NSURLCache setSharedURLCache:sharedCache];
        [sharedCache release];
    
    If you are using ARC replace 
        [sharedCache release];
    with
        sharedCache = nil;
    

    希望对你有帮助。

    【讨论】:

    • 谢谢,我会试试的。有些是图像,有些是 word 文档,有些是 HTML 文件、电影等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2014-03-03
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多