Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用AFN操作连续下载多个文件…内存不足_Ios_Objective C_Multithreading_Automatic Ref Counting_Out Of Memory - Fatal编程技术网

Ios 使用AFN操作连续下载多个文件…内存不足

Ios 使用AFN操作连续下载多个文件…内存不足,ios,objective-c,multithreading,automatic-ref-counting,out-of-memory,Ios,Objective C,Multithreading,Automatic Ref Counting,Out Of Memory,注意:我使用的是ARC 我有一些代码可以向http服务器请求一个文件列表(通过JSON)。然后,它将该列表解析为模型对象,用于将下载操作(用于下载该文件)添加到不同的nsoperationqueue,然后在添加完所有这些操作(队列开始暂停)后,启动队列并等待所有操作完成,然后再继续。(注意:这都是在后台线程上完成的,以免阻塞主线程) 以下是基本代码: NSURLRequest* request = [NSURLRequest requestWithURL:parseServiceUrl]; AF

注意:我使用的是ARC

我有一些代码可以向http服务器请求一个文件列表(通过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都变弱。我试着添加一个自动释放池,我试着使实际的文件域对象也变得很弱,但内存仍然在不断攀升

我曾经运行过Instruments,没有发现任何泄漏,但它从来没有达到一个点,即在内存耗尽之前,所有文件都已下载,并出现了一个大的“无法分配区域”错误。看看分配,我看到了一堆连接:didFinishLoading和连接:didReceiveData方法,但它们似乎从未被放弃过。不过,我似乎无法再调试它了


我的问题:为什么内存不足?什么东西没有被解除分配?我怎样才能让它这样做?

这里有一些事情。最大的问题是,您正在下载整个文件,将其存储在内存中,然后在下载完成后将其写入磁盘。即使只有一个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
仅在非常有限的情况下有用。一般来说,如果您不确定是否需要,您就不需要了。

您正在下载哪种类型的文件?如果您正在处理图像或视频,则需要清除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;

希望它能对你有所帮助。

在一位朋友的帮助下,我解决了这个问题

问题实际上出现在第一段代码中:

[_dlQueue waitUntilAllOperationsAreFinished];
显然,等待所有操作完成意味着这些操作也不会被释放

取而代之的是,我在队列中添加了一个最终操作,该操作将执行最终处理和回调,现在内存更加稳定

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

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

伟大的答案与三个最佳实践建议!谢谢我知道如何使用NSOutputstream,但出于安全原因,我需要使用文件保护将数据写入磁盘。此外,代码中的_u弱和autoreleasepool区域是我尝试查看使某些事情弱是否会产生任何影响,或者autoreleasepool是否会产生任何影响,以获得所需的内容保留…释放。但是,这些组合都不起作用,包括你在这里建议的方式。“它不起作用”对诊断没有帮助。你所期待的发生了什么或没有发生什么?如果我们没有足够的信息,我们就帮不上忙。没有发生的是问题没有解决。记忆一直在上升,从未释放过。我在这里发布的代码是在修改了一堆带有uu弱和自动释放池的地方之后发布的。我可能应该把它恢复到我开始试验之前的状态。另外,当我在完成块之外创建弱引用时,它们在执行块时就已经被释放了……因此它们是无用的。twitter上有人提到self被保留,因为我正在使用[self updateProgress]因此,它将控制器保留在完成块中,该块由操作拥有,该操作由控制器拥有的operationqueue拥有……因此存在保留循环。当我将[self updateProgress]代码直接移动到块中时,我必须看看会发生什么。请注意,删除[self updateProgress]并不能解决问题,但我会尝试一下。有些是图像,有些是word文档,有些是HTML文件、电影等。