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

标签 ios image memory memory-management

我在将大量大图像(来自相机)依次循环保存到文件系统时遇到了一个奇怪的问题。

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

有人可以解释一下如何避免这种情况或在每次循环后释放内存吗?

顺便说一句,我正在 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);
    }
}

最佳答案

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

关于ios - 在 iOS 上一个接一个地保存大图像内存释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9293911/

相关文章:

ios - UITextView *font* 属性在 iOS 9 中是可选的。默认情况下它是 nil 吗?

css - 图片覆盖完整的 div CSS

mysql - Java MySQL查询线程不断增加内存使用

c++ - 使用 Rcpp 函数后 R Studio 崩溃

ios - 如何从 Rest API 发送推送通知

ios - AFNetworking 需要绕过 ssl 检查

ios - 从 iOS 图像中提取的 GPS 值未显示正确的正值或负值

ubuntu - Pandoc 和 Rstudio Knitr 内存泄漏

iphone - 如何在 iOS 上创建这样的联系人字段条目?

javascript - 如何在同步 Javascript 中查找异步图像状态