2012-02-15 47 views
1

我有一个奇怪的问题,在循环中一个接一个地保存大量图像(从相机)到文件系统。在iOS上一个接一个地保存大图像内存释放

如果我在每个循环中放置了[NSThread sleepForTimeInterval:1.0];,那么每次图像处理后都会释放内存。但没有睡眠时间间隔,内存分配增加到屋顶以上,最终应用程序崩溃...

有人请解释如何避免这种情况或每个循环后释放内存?

顺便说一句,我在iOS 5开发...

这是我的代码:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    for (NSDictionary *imageInfo in self.imageDataArray) { 

     [assetslibrary assetForURL:[NSURL URLWithString:imageUrl] resultBlock:^(ALAsset *asset) { 
      CGImageRef imageRef = [[asset defaultRepresentation] fullResolutionImage]; 
      if (imageRef) { 
       [sharedAppSettingsController saveCGImageRef:imageRef toFilePath:filePath]; 
       imageRef = nil; 
       [NSThread sleepForTimeInterval:1.0]; 
       //CFRelease(imageRef); 
      } 
     } failureBlock:^(NSError *error) { 
      NSLog(@"booya, cant get image - %@",[error localizedDescription]); 
     }]; 

    } 

    // tell the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     //do smth on finish 
    }); 
}); 

这是保存CGImage到FS的方法:

- (void)saveCGImageRef:(CGImageRef)imageRef toFilePath:(NSString *)filePath { 
    @autoreleasepool { 
     CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:filePath]; 
     CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypeJPEG, 1, NULL); 
     CGImageDestinationAddImage(destination, imageRef, nil); 

     bool success = CGImageDestinationFinalize(destination); 
     if (!success) { 
      NSLog(@"Failed to write image to %@", filePath); 
     } 
     else { 
      NSLog(@"Written to file: %@",filePath); 
     } 
     CFRelease(destination); 
    } 
} 
+0

你是否将你的循环包装在@autorelease {}块中? – Nyx0uf 2012-02-15 13:06:42

+0

你可以发布一些代码 – 2012-02-15 13:24:32

+0

我已经将代码封装在循环内部和外部,没有任何效果。应用程序仍然消耗超过20MB的内存和崩溃。还有什么要寻找? – 2012-02-15 13:25:35

回答

2

问题是您在for循环中调用“assetForURL”。这种方法将开始在一个单独的线程上同时加载所有图像。您应该开始加载1个图像,并在完成块中继续加载下一个图像。我建议你使用某种递归。

+0

谢谢,那工作... – 2012-02-21 07:32:07

0

我刚刚发现问题不在于saveImageRef方法,但带有ALAssetRepresentation对象:

CGImageRef imageRef = [[asset defaultRepresentation] fullResolutionImage]; 

imageRef从照片库读取每个原始图像后分配大量的内存。这是合乎逻辑的。

但我希望这个imageRef对象在每个循环结束时释放,而不是每当ARC决定释放它时。

所以我试图imageRef = nil;后每个循环,但没有任何改变。

是否有任何其他方式释放每个循环结束时分配的内存?