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

时间:2012-02-15 13:00:39

标签: ios image memory memory-management

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

如果我在每个循环中放置[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);
    }
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

CGImageRef imageRef = [[asset defaultRepresentation] fullResolutionImage];
从Photo库中读取每个原始图像后,

imageRef会分配大量内存。这是合乎逻辑的。

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

所以我在每次循环后尝试imageRef = nil;但没有任何改变。

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