blocks and retaining CoreFoundation objects
blocks and retaining CoreFoundation objects
- Subject: blocks and retaining CoreFoundation objects
- From: Roland King <email@hidden>
- Date: Tue, 09 Aug 2011 14:43:13 +0800
I have a slow image conversion which I want to throw onto a background thread using GCD. The actual method which does the conversion takes a CGImageRef and the code looks like this
-(void)convert:(CGImageRef)image withBlock:(ImageResizedBlock)callbackBlock
{
dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^{
CGImageRef converted = [ self createConvertedImage:image ];
callbackBlock( converted );
CGImageRelease( converted );
} );
};
I quickly found that whereas NSObject(s) are retained by the block, CoreFoundation objects don't appear to be, so image can be, and usually is, released before the block runs, causing an exception.
One way to fix this is to add a CFImageRetain() before the dispatch_async() and a CFImageRelease() inside the block at the same place converted is released, which works, but I for some reason don't like, probably because the retain is outside the block and the release is inside it and it seems odd to me.
After a bit of googling I came across some posts which explained Block_Copy() would treat a variable adorned with __attribute__((NSObject)) similarly to NSObjects and retain them. So changing the method signature to this
-(void)convert:(__attribute__((NSObject))CGImageRef)image withBlock:(ImageResizedBlock)callbackBlock
appears to do the right thing in my testing, the CGImageRef is CFRetain()ed when the block is enqueued and I assume CFRelease()d later. I prefer this syntax, as I find it self-documenting;
I can't find anywhere apart from blog posts and the block specification itself which says this works. Does anyone know if it's officially supported, for gcc and clang and something that apple is likely to support going forward into ARC etc. _______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden