Question

I'm trying to set a property like so -

-interface:

@property (readwrite, assign) CGColorRef otherBallColor;

-someMethod:

CGColorRef ballColor = [UIColor colorWithRed:255.0/256.0 green:165.0/256.0 blue:239.0/256.0 alpha:1.0].CGColor;  
[self setOtherBallColor:ballColor];

As soon as I try to access the value it crashes -

-someOtherMethod (drawRect in this case):

CGContextSetFillColorWithColor(context, otherBallColor);

But if in the "someMethod" I do -

CGColorRef ballColor = [UIColor blueColor].CGColor;

... it all works fine. Can anyone explain what's going on?

Many thanks (PS, quite new to Objective-C, tho not programming in general)

Was it helpful?

Solution

You must retain returned CGColor, your [UIColor colorWith...] creates an auto-released instance, so, when it is out of scope (autoreleased I mean), corresponding CGColor is released as well.

I'd recommend you to use UIColor instead of CGColorRef if i is possible in this case.

OTHER TIPS

Talk about a late answer, but I've got an alternative solution to this particular problem, which I ran into a little while ago. I found this question before the solution, so I figured I'd throw in my two cents. It turns out that UIColor has an instance method called setFill, which sets the receiver as the current context fill color. So you could write:

CGContextRef myContext = UIGraphicsGetCurrentContext();
[[UIColor colorWithRed:255.0/255.0 green:165.0/255.0 
                  blue:239.0/255.0 alpha:1.0] setFill];
CGContextFillPath(myContext);

I find this a cleaner solution, because you don't have to worry about retaining or subsequently releasing any CGColors. In fact, you don't even have to deal with any Core Graphics fill color setting commands, like CGContextSetFillColorWithColor.

You can check out the - (void)setFill method in more detail in the UIColor Apple documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top