Pregunta

I have an iPhone app where I'm "adding" a lot of CGColors together by breaking them down into their components, averaging the components, and then making a new color with the new components. When I run this code, Instruments finds that I'm leaking lots of CGColors, and the app runs slowly.

I feel like I could solve the memory leak issue if there were a way to do what I'm doing without using CGColorCreate(colorspace, components) every time.

This is the code for the color "adding"

const CGFloat *cs=CGColorGetComponents(drawColor);
const CGFloat *csA=CGColorGetComponents(add->drawColor);
CGFloat r=(cs[0]*w+csA[0]*aW)/1;
CGFloat g=(cs[1]*w+csA[1]*aW)/1;
CGFloat b=(cs[2]*w+csA[2]*aW)/1;
CGFloat components[]={r, g, b, 1.f};
drawColor=CGColorCreate(CGColorSpaceCreateDeviceRGB(), components);

Any help would be really appreciated, even if the help is "add the colors less often." I'm sure I'm not the only person trying to modify CGColors.

EDIT: So, rob's comment put me on the right track, but I'm getting malloc double free errors because the method with the color adding is called multiple times before a new drawColor is assigned. Is there a way to check whether drawColor exists before I release it? Here is the new relevant code.

CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
CGColorRelease(drawColor);
drawColor=CGColorCreate(colorSpace, components);
CGColorSpaceRelease(colorSpace);
¿Fue útil?

Solución

If you're leaking CGColor objects, the first step to solving your problem is to stop leaking them. You need to call CGColorRelease when you're done with a color object. For example, you are obviously leaking the drawColor object in your example code. You should be doing this:

CGColorRelease(drawColor);
drawColor=CGColorCreate(CGColorSpaceCreateDeviceRGB(), components);

to release the old object referenced by drawColor before you assign the new object to drawColor.

CGColor objects are immutable, so you won't be able to just modify your existing objects.

Otros consejos

Pretty sure you just need to CGColorRelease(drawColor) to prevent the leak. See how that helps your performance.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top