内存泄漏在循环中使用dataWithContentsOfURL

Ric*_*nes 2 cocoa-touch memory-leaks block objective-c ios

我正在使用Xcode 4.6.3和iOS 5.5/6.1.6.

我正在使用后台线程从服务器向iOS设备加载大量的jpg.

dispatch_async(kBgQueue, ^
               {
                   // get the array of filenames to download
                   NSURL* url = [NSURL URLWithString:webPath];
                   NSArray* theArray = [NSArray arrayWithContentsOfURL:url];
                   if( theArray )
                   {
                       dispatch_async(dispatch_get_main_queue(), ^{
                           // disable screen buttons
                           [self setButtons:false];
                       });

                       [self loadImagesFromList:theArray sourceBundle:bundlePath destBundle:localBundlePath manager:manager];

                       if (!stopFlag) {
                           // if no memory error has occurred
                           NSLog(@"calling refresh after load_images");
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [self refresh];
                           });
                       }
                       theArray = nil;
                   }
                   else
                   {
                       NSLog(@"Error loading bundle");
                   }
               });
Run Code Online (Sandbox Code Playgroud)

背景方法:

-(void)loadImagesFromList:(NSArray *)theArray
             sourceBundle:(NSString *)bundlePath
               destBundle:(NSString *)localBundlePath
                  manager:(NSFileManager *)manager {

    // initialize the progress and activity indicator
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.activityIndictor startAnimating];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        [self.progressIndictor setProgress:0 animated:NO];
    });

    NSURL *url;
    NSString *srcFile;
    NSString *destFile;
    NSError *error = nil;

    int counter = 0;
    float prog = 0;
    float increment = 1.0 / [theArray count];
    float stepSize = [theArray count] / 10;

    for (NSString *file in theArray)
    {
        if (stopFlag) {
            NSLog(@"I see stopFlag = true, counter = %d, prog = %f", counter, prog);
            return;
        }
        srcFile = [bundlePath stringByAppendingPathComponent:file];
        destFile = [localBundlePath stringByAppendingPathComponent:file];

        counter += 1;
        prog += increment;
        if (counter == stepSize) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.progressIndictor.progress = prog;
            });
            counter = 0;
        }

        // only download if file isn't already here
        BOOL fileExists = [manager fileExistsAtPath:destFile]; // check if we already have it
        if (!fileExists) {
            // jpg or folder check
            if ([[destFile pathExtension] isEqualToString:@"jpg"]) {
                url = [NSURL URLWithString:srcFile];
                data = [NSData dataWithContentsOfURL:url
                                             options:0
                                               error:&error];

                [data writeToFile:destFile options:NSDataWritingAtomic error:&error];
                data = nil;
            } else {
                [manager createDirectoryAtPath:destFile withIntermediateDirectories:YES attributes:nil error:&error];
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果文件存在,循环将拉开数组并退回到主线程ok.如果缺少任何文件,下载/写入部分似乎会咀嚼RAM并导致低内存警告触发.它需要几千个文件才能完成.

我已经尝试在循环外声明变量,甚至在主线程中完成整个事情以测试是否导致泄漏.我尝试使用备用dataWithContentsOfURL:options:错误调用.我试过了仪器,但它确实很慢并经常崩溃.在崩溃之前,它确实显示分配上升,上升,缓慢上升.

经过几天,我很难过.

Rob*_*Rob 7

我建议的第一件事是使用a @autoreleasepool来控制消耗的峰值内存量.现在,您将内容下载到NSData自动释放对象中,完成后,您将nil对该变量进行简单标记,一旦自动释放池耗尽,该变量将被解除分配(直到loadImagesFromList完成后才会发生) .通过(a)在for循环内移动变量声明; 并且(b)将其包装成一个@autoreleasepool,当你的个人下载完成后,你的记忆将被解除分配.

-(void)loadImagesFromList:(NSArray *)theArray
             sourceBundle:(NSString *)bundlePath
               destBundle:(NSString *)localBundlePath
                  manager:(NSFileManager *)manager {

    // initialize the progress and activity indicator
    dispatch_async(dispatch_get_main_queue(), ^{
        // your UI update here
    });

    int counter = 0;
    float prog = 0;
    float increment = 1.0 / [theArray count];
    float stepSize = [theArray count] / 10;

    for (NSString *file in theArray)
    {
        @autoreleasepool {
            if (stopFlag) {
                NSLog(@"I see stopFlag = true, counter = %d, prog = %f", counter, prog);
                return;
            }

            NSString *srcFile = [bundlePath stringByAppendingPathComponent:file];
            NSString *destFile = [localBundlePath stringByAppendingPathComponent:file];

            counter += 1;
            prog += increment;
            if (counter == stepSize) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.progressIndictor.progress = prog;
                });
                counter = 0;
            }

            // only download if file isn't already here
            BOOL fileExists = [manager fileExistsAtPath:destFile]; // check if we already have it
            if (!fileExists) {
                NSError *error = nil;

                // jpg or folder check
                if ([[destFile pathExtension] isEqualToString:@"jpg"]) {
                    NSURL *url = [NSURL URLWithString:srcFile];
                    NSData *data = [NSData dataWithContentsOfURL:url
                                                         options:0
                                                           error:&error];

                    [data writeToFile:destFile options:NSDataWritingAtomic error:&error];
                } else {
                    [manager createDirectoryAtPath:destFile withIntermediateDirectories:YES attributes:nil error:&error];
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)