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;
}
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!
You can do this:
CGColorRef color = (CGColorRef)[(id)CGColorCreate(colorSpace, components) autorelease];
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With