Re: ARC + return of autoreleased CFType
Re: ARC + return of autoreleased CFType
- Subject: Re: ARC + return of autoreleased CFType
- From: Ken Thomases <email@hidden>
- Date: Wed, 19 Oct 2011 08:58:37 -0500
On Oct 19, 2011, at 8:04 AM, John Pannell wrote:
> I've got a category on NSColor to return a CGColor value. Source looks like this:
>
> - (CGColorRef)CGColor
> {
> NSColor *colorRGB = [self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
> CGFloat components[4];
> [colorRGB getRed:&components[0] green:&components[1] blue:&components[2] alpha:&components[3]];
> CGColorSpaceRef theColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
> CGColorRef theColor = CGColorCreate(theColorSpace, components);
> CGColorSpaceRelease(theColorSpace);
> return theColor;
> }
>
> My issue is with the final line: the CGColor has a retain count of 1, as it was made with a "Create" function. Following Cocoa convention, I'd want to cast the return value and autorelease it, but the autorelease call is not allowed under ARC. Xcode is doing its best to help me figure out how to return the value, but the only thing I can get it to not squeak about is this:
>
> return (__bridge_retained CGColorRef)(__bridge_transfer id)theColor;
>
> which does not seem reasonable to me. Can anyone suggest the proper syntax to return an "autoreleased" CGColorRef from this function?
Here's one possibility that I'm not sure will work:
* Create a utility class to hold a CFTypeRef. It will CFRetain() it during its init method and CFRelease() it in its -dealloc.
* Instantiate an instance of that class with theColor.
* Store the address of that instance to an __autoreleasing-qualified variable.
* CGColorRelease(theColor), leaving the instance of the utility class as the only owner.
* Return theColor directly with no other attempt to manage its lifetime.
I _think_ that ARC will autorelease the utility object due to it being referenced by the __autoreleasing-qualified pointer, rather than releasing it. And since that object survives for the lifetime of the innermost autorelease pool and owns theColor, theColor survives that long, too.
The use of the utility class and the extra object is cumbersome, but that may be the best that you can do. Also, it resolves the hinky-ness of using -autorelease on a non-toll-free-bridged CFType (although I believe that is safe). Also, the utility class is general purpose and can be used in other similar circumstances.
Regards,
Ken
_______________________________________________
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