ios7 - 无法在 iOS 上将 CIImage 保存到文件而不发生内存泄漏

标签 ios7 memory-leaks uikit core-image

以下代码片段保存 CIImage使用 UIImage 到磁盘.

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSString* filename = @"Test.png";

    UIImage *image = [UIImage imageNamed:filename];

    // make some image processing then store the output
    CIImage *processedImage = [CIImage imageWithCGImage:image.CGImage];

#if 1// save using context

    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgiimage = [context createCGImage:processedImage fromRect:processedImage.extent];
    image = [UIImage imageWithCGImage:cgiimage];

    CGImageRelease(cgiimage);

#else

    image = [UIImage imageWithCIImage:processedImage];

#endif

    // save the image

    NSString *filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[@"../Documents/" stringByAppendingString:filename]];

    [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
}

但是,它泄露了 CGImageRef即使通过调用 CGImageRelease 来释放它

enter image description here

如果该行带有 #if 1更改为#if 0UIImage直接从 CIImage 创建并且没有内存泄漏,但是 UIImage未保存到磁盘

最佳答案

将保存包装在自动释放池中:

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSString* filename = @"Test.png";

    UIImage *image = [UIImage imageNamed:filename];

    // make some image processing then store the output
    CIImage *processedImage = [CIImage imageWithCGImage:image.CGImage];

    @autoreleasepool {
        CIContext *context = [CIContext contextWithOptions:nil];
        CGImageRef cgiimage = [context createCGImage:processedImage fromRect:processedImage.extent];
        image = [UIImage imageWithCGImage:cgiimage];

        CGImageRelease(cgiimage);

        // save the image
        NSURL *documentsDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
        NSURL *fileURL = [documentsDir URLByAppendingPathComponent:filename];

        [UIImagePNGRepresentation(image) writeToURL:fileURL atomically:YES];
    }
}

另请注意,我更新了您检索文档目录的方式以适用于 iOS 8 ( more info )。

关于ios7 - 无法在 iOS 上将 CIImage 保存到文件而不发生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826755/

相关文章:

ios7 - ios 7+ 中的 GStreamer 编译错误

OSX El Capitan 上的 Xcode 7.1,iOS 7 模拟器 - 它应该可以工作吗?

swift - UIAlertController 中的内存泄漏关闭

objective-c - objective-c :非空实例方法中的内存泄漏

ios - 从 Xcode 5 支持旧版本的 iOS

xcode构建错误框架未找到

android - volley 请求的匿名监听器导致内存泄漏

iphone - UIView类中addSubview和insertSubview的区别

ios - 在这种情况下,如何改变 UIActivityViewController 使用的项目?

ios - 如何使用 CFTimeInterval 为动画指定开始时间?