CGContextClipToMask adds ref count but nowhere to release.

CGContextRef context = CGBitmapContextCreate(NULL, 40, 40, 8, 0, grayColorSpace, kCGImageAlphaOnly); CGImageRef image = CGBitmapContextCreateImage(context); const CFIndex startRef = CFGetRetainCount(image); CGContextClipToMask(context, CGRectMake(0, 0, 40, 40), image); // This will cause ref retained. const CFIndex endRef = CFGetRetainCount(image); NSLog(@"start %@ end %@", @(startRef), @(endRef)); // <----- 1 2 CFRelease(image); CFRelease(context);

Replies

I re-format this. ```objective-c CGContextRef context = CGBitmapContextCreate(NULL, 40, 40, 8, 0, grayColorSpace, kCGImageAlphaOnly); CGImageRef image = CGBitmapContextCreateImage(context); const CFIndex startRef = CFGetRetainCount(image); CGContextClipToMask(context, CGRectMake(0, 0, 40, 40), image); // This will cause ref retained. const CFIndex endRef = CFGetRetainCount(image); NSLog(@"start %@ end %@", @(startRef), @(endRef)); // <----- 1 2 CFRelease(image); CFRelease(context); ```

When you query an object's retain count, you're just going to confuse yourself. Are you seeing a persistent leak somewhere? The code you posted is fine. If the context is retaining the image, then it's the context's responsibility to release it. The general philosphy is that memory management is local. You make sure you get yours right and you assume that other code gets its right. You don't need a global view of what everybody is doing.

Alright maybe I'm over focusing on these glitches.

Actually I just wrote a little wrapper that help me release CFObjects automatically on scope exiting. Code is as follows could you give me some advise?

@interface ACCoreFoundationGuard() {
CFTypeRef ref;
#ifdef DEBUG
CFIndex refCount;
#endif
}
@end

@implementation ACCoreFoundationGuard
/**
* Initialize with a pointer.
* The pointer would be `free`ed on object dealloced.
*/
-(instancetype) initWithCFObject:(CFTypeRef) obj {
self = [super init]; ref = obj;
#ifdef DEBUG
// To record ref count on starting being managed.
self->refCount = CFGetRetainCount(ref);
#endif
return self;
}

-(void) dealloc {
if(ref) {
#if DEBUG
CFIndex refCnt = CFGetRetainCount(ref);
NSAssert(refCnt == self->refCount, @"Current ref count may have leaks.");
#endif
CFRelease(ref);
}
}
@end