I’m in the process of converting my project to using ARC. I have a category on NSColor with a method that returns an autoreleased CGColor representation:
@implementation NSColor (MyCategory)
- (CGColorRef)CGColor
{
NSColor *colorRGB = [self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
CGFloat components[4];
[colorRGB getRed:&components[0]
green:&components[1]
blue:&components[2]
alpha:&components[3]];
CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGColorRef theColor = CGColorCreate(space, components);
CGColorSpaceRelease(space);
return (CGColorRef)[(id)theColor autorelease];
}
@end
What is the correct way to do this with ARC? I don’t want to return a retained CGColor.
The ARC converter in XCode suggest using
return (CGColorRef)[(__bridge id)theColor autorelease];
but that results in the following error message:
[rewriter] it is not safe to cast to ‘CGColorRef’ the result of
‘autorelease’ message; a __bridge cast may result in a pointer to a
destroyed object and a __bridge_retained may leak the object
CGColoris a Core Foundation object. You should not attempt to useautoreleasewith it. Instead, you should rename your methodcopyCGColorand return a retained object.Auto-releasing is an Objective-C concept. It does not exist at the Core Foundation level.
Since
CGColoris not toll-free bridged to any Objective-C class, it is very weird to try to autorelease it (even if that might work).Update a few years later
There is now CFAutorelease() at the CoreFoundation level (available since Mavericks and iOS 7).