Freddy
Freddy

Reputation: 820

How to clear CGBitMapContext without causing memory leak?

I have a CGBitmap context where everything that gets draw on the screen is saved. When i press a button called reset I want everything that is draw in the UIView to get deleted. If is set both cacheBitmap and cache context to nil it will clear the view, however it will cause a memory leak since I'm not releasing them. Calling free and CFRelease does however cause the memory leak to disappear but, the view doesn't get cleared. Is there any way to clear the view while preventing the memory leak issue?

  // init method
    cacheBitmap = malloc( bitmapByteCount );
    if (cacheBitmap == NULL){
        return NO;
    }

    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little;
    colorSpace = CGColorSpaceCreateDeviceRGB();

    cacheContext = CGBitmapContextCreate (cacheBitmap, size.width*scaleFactor, size.height *scaleFactor, 8, bitmapBytesPerRow, colorSpace, bitmapInfo);

       CGContextScaleCTM(cacheContext, scaleFactor, scaleFactor);


  CGContextSetRGBFillColor(cacheContext, 0, 0, 0, 0.0);
   CGContextFillRect(cacheContext, (CGRect){CGPointZero, CGSizeMake(size.height*scaleFactor, size.width*scaleFactor)});

    return YES;
}

-(void)clear{

    cacheContext = nil;
    cacheBitmap = nil;
    CGContextRelease(cacheContext);
    free(cacheBitmap);
    CGColorSpaceRelease(colorSpace);


    [self initContext:framsize];
    [self setNeedsDisplay];

}

Upvotes: 1

Views: 385

Answers (1)

BoilingLime
BoilingLime

Reputation: 2267

you should try to call UIGraphicsEndImageContext() once you finish to work with your context.

have look over here : https://developer.apple.com/library/ios/documentation/uikit/reference/UIKitFunctionReference/Reference/reference.html#//apple_ref/c/func/UIGraphicsEndImageContext

Upvotes: 1

Related Questions