Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CIContext Memory Leak even with released CIImageRefs

I am using the solution found here to blur an image with CIGaussianBlur. However, I am getting a memory leak that I cannot resolve. I originally was using not using CIContext as a property, but thought that could be the issue to no avail. I also was using a CGRect from the output image but changed this to try and close the leak, once again did not work.

I believe I am releasing all that I need to (ARC is on), so what could be causing the memory leak?

    CIFilter *gaussianBlurFilter = [CIFilter filterWithName: @"CIGaussianBlur"];
    CGImageRef cgimage = [image CGImage];
    [gaussianBlurFilter setValue:[CIImage imageWithCGImage:cgimage] forKey:kCIInputImageKey];
    [gaussianBlurFilter setValue:@10 forKey:kCIInputRadiusKey];
    CIImage *outputImage = [gaussianBlurFilter outputImage];
    if (imageContext == nil) {
        imageContext = [CIContext contextWithOptions:nil];
    }
    CGImageRef cgimg     = [imageContext createCGImage:outputImage fromRect:CGRectMake(0.0, 0.0, 25.0, 25.0)];
    UIImage *blurredImage       = [UIImage imageWithCGImage:cgimg];

    pictureIncognito.image = blurredImage;
    pictureIncognito.layer.cornerRadius = pictureIncognito.frame.size.width / 2.0;
    pictureIncognito.layer.masksToBounds = YES;
    pictureIncognito.layer.borderWidth = 1.0;
    pictureIncognito.layer.borderColor = [[UIColor whiteColor] CGColor];

    CGImageRelease(cgimage);
    CGImageRelease(cgimg);

enter image description here

like image 321
willhblackburn Avatar asked Apr 18 '14 18:04

willhblackburn


1 Answers

EDIT:

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/Reference/reference.html#//apple_ref/c/func/CGContextRelease

I came across this today. You do, in fact, need to release the context using this special function.


My answer is derived from this question.

As an observation, I don't think you need this line:

CGImageRelease(cgimage);

You don't actually own that object (the method you use to set it doesn't have 'get', 'alloc', 'create', or 'new' in it).

I don't have a lot of experience with CGImage, but I would imagine that the context still exists somewhere in the Objective-C runtime, and that the context is somehow retaining the image itself. So, setting the context (and everything else) to nil might fix the issue.

Of course, if this works, then it means that you would be creating a new context for each image you blurred, and it might affect your ability to modify the image later... but it might solve the memory leak!

like image 156
Gazzini Avatar answered Sep 21 '22 13:09

Gazzini