在iOS上一个接一个地保存大图像内存释放

在iOS上一个接一个地保存大图像内存释放,ios,image,memory,memory-management,Ios,Image,Memory,Memory Management,我有一个奇怪的问题,在循环中一个接一个地将大量大图像(从相机)保存到文件系统 如果我放置[NSThread sleepForTimeInterval:1.0]在每个循环中,内存在每次图像处理后都会被释放。但如果没有睡眠时间间隔,内存分配就会超过上限,最终应用程序崩溃 有人能解释一下如何避免这种情况或在每次循环后释放内存吗 顺便说一句,我正在开发iOS 5 这是我的代码: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORIT

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

如果我放置
[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);
    }
}

我刚刚发现问题不在saveImageRef方法中,而是在ALAssetRepresentation对象中:

CGImageRef imageRef = [[asset defaultRepresentation] fullResolutionImage];
imageRef
从照片库中读取每个原始图像后分配大量内存。这是合乎逻辑的

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

所以我试着
imageRef=nil在每个循环之后,但没有任何更改


是否有其他方法可以在每个循环结束时释放分配的内存?

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

是否将循环包装在@autorelease{}块中?我将代码包装在循环内外,但没有任何效果。应用程序仍然消耗超过20MB的ram,并且会崩溃。还有什么要找的吗?如果我做错了smth,有人能看一下代码吗?