Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autorelease CGColorRef

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;
}
like image 950
Charith Nidarsha Avatar asked Aug 17 '10 10:08

Charith Nidarsha


3 Answers

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!

like image 56
Max Seelemann Avatar answered Oct 15 '22 18:10

Max Seelemann


You can do this:

CGColorRef color = (CGColorRef)[(id)CGColorCreate(colorSpace, components) autorelease];
like image 6
Alex Kantaev Avatar answered Oct 15 '22 17:10

Alex Kantaev


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;
like image 3
mvds Avatar answered Oct 15 '22 18:10

mvds