views:

139

answers:

4

Hi all,

I have a method that returns CGColorRef instance created by CGColorCreate method. I need to autorelease the color return from this method. Does anyone know how to do this?

//red,green,blue are from 0-255 range

+(CGColorRef) getColorFromRed:(int)red Green:(int)green Blue:(int)blue Alpha:(int)alpha
{
    CGFloat r = (CGFloat) red/255.0;
    CGFloat g = (CGFloat) green/255.0;
    CGFloat b = (CGFloat) blue/255.0;
    CGFloat a = (CGFloat) alpha/255.0;  
    CGFloat components[4] = {r,g,b,a};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef color = CGColorCreate(colorSpace, components);
    CGColorSpaceRelease(colorSpace);

    //CGColorRelease(color);
    // I need to auto release the color before returning from this.

    return color;
}
+1  A: 

You cannot. Autorelease pools work on objects listening to the release message, and a CGColorRef is not such an object.

You could rewrite things to return a UIColor, by doing

UIColor *ret = [UIColor colorWithCGColor:color]; // ret will be autoreleased
CGColorRelease(color);
return ret;
mvds
+1  A: 

You can do this:

CGColorRef color = (CGColorRef)[(id)CGColorCreate(colorSpace, components) autorelease];
MeGr
A: 

Use toll-free bridge:

return [(UIColor *)color autorelease];

Or you can user + (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha method and then do return [myColor CGColor];

beefon
UIColor and CGColorRef are not documented to be toll-free bridged. You can use +colorWithCGColor: to convert to a UIColor though.
JeremyP
Sorry, you are right.
beefon
+1  A: 

You cannot directly, as mvds said. Also UIColor and CGColorRef are not tool-free bridged -- why the converter functions then? However (and while I don't recommend it -- use UIColor instead!) there is a trick to do so:

Create a autoreleased UIColor object and return it's CGColor. Like so:

return [UIColor colorWith... ].CGColor;

This will return a regular CGColorRef object that is bound to it's UIColor. Which means that if the UIColor is released in the autorelease loop, it's CGColorRef will be released as well -- unless it has been retained somewhere else using a CGRetain(...), which the caller of your method should have done if it wanted to keep the color. As such the CGColorRef is pseudo-autoreleased...

Still: I would not recommend doing so. Use UIColor directly!

Max Seelemann
Although I must admit this is quite ingenious, it introduces (chances for) bugs that are almost impossible to find in your own code 6 months from now.
mvds
right, this is why I don't recommend using it.
Max Seelemann