Assigning an existing CGColor to a CGColor property works in iOS Simulator, not iOS device. Why?

RLH picture RLH · Feb 9, 2012 · Viewed 9.5k times · Source

I know how to fix the problem that I am about to outline, however, I am a bit baffled as to why the code scenario works in the iOS simulator but not on my iPad.

I have a method that checks various properties, and then sets the background color of a CALayer depending on the state of a property. The following code is similar to my method of color assignment:

//This will be the CALayer BGColor...
CGColor c = UIColor.blueColor.CGColor; //Blue is the default
switch (myState)
{
    case state_one:
        c = UIColor.greenColor.CGColor;
        //... more code ...
        break;
    case state_two:
        c = UIColor.redColor.CGColor;
        //... more code ...
        break;
    case state_three: //multiple cases are like the state_three case.
        //Other code, but I don't need to assign the color.  Blue works...
}

myCALayer.backgroundColor = c; //Oh-noes!!! Here we get the dreaded EXC_BAD_ACCESS on iPad
//...more code dealing with the layer.

The code above works without trouble in the Simulator. However, when I run the application on my iPad, it crashes at the backgroundColor assignment.

I can fix this by getting rid of the CGColor variable and assigning the background color from directly within my switch/case statement, and that's what I'm planning on doing.

However, I am curious. Why would this work in one environment and not the other?

UPDATE

Couple things. First, it's worth mentioning that this is an ARC project, using Xcode 4.2, targeting iOS 5 devices. Also, my color assignement code isn't entirely what it looks like because I have a series of defines that I use to set these colors because they are referenced all throughout my application.

This is what a few of the #define statements looks like:

#define BLUE  [UIColor colorWithRed:8.0/255.0 green:80.0/255.0 blue:150.0/255.0 alpha:1.0].CGColor
#define GREEN (UIColor.blueColor.CGColor)
//...and there are about 6 other colors

I tried to simplify my code because the compiler should replace the refs to my refs to my defines. Still, it's worth mentioning just in case.

Answer

ugiflezet picture ugiflezet · Dec 1, 2012

Because of ARC the color is released too early in the end of the method.

i use: CGColorRetain

CGColorRef whiteColor = CGColorRetain([UIColor colorWithRed:1.0 green:1.0
                                         blue:1.0 alpha:1.0].CGColor);