iosobjective-ccgcolor

About CGColor/definition


In a class I have a variable myColor of type CGColorRef declared as follow:

@implementation MyClass
{
    .......
    CGColorRef myColor;
    .......

Here are two lines of Objective C code:

First line:

myColor=[UIColor orangeColor].CGColor;

Second line:

myColor=[UIColor colorWithRed:1.000 green:0.500 blue:0.000 alpha:1.000].CGColor;

I first expected them to be equivalent, but they are not.

I know they are not equivalent, because when I use the first one my program works. And when I use the second one it crashes later down the road. Showing more code here would be totally irrelevant to the question.

Can someone explain the difference? That will hopefully allow me to modify my code and be able to use the second line.

Just for reference, it crashes in (with: Thread 1: EXC_BAD_ACCESS (code=1, address=0x881b370e0)):

- (void)drawRect:(CGRect)rect
{
    .......
    CGContextSetStrokeColorWithColor(context,myColor); // Crash here !!!
    CGContextStrokeEllipseInRect(context, rectangle);
    .......
}

Solution

  • Crash is because may be you don't have strong ref (property) of myColor object. You might has assign property

    Reason why [UIColor orangeColor] works but not [UIColor colorWithRed...

    When you use [UIColor orangeColor], you don't create the object; you get a reference to it and something else manages its life cycle.

    When you init a new UIColor object, you're responsible for making sure it is still valid when used. "assign" doesn't increase the object's reference count; "strong" does.

    Hope it is helpful

    EDIT

    Decleare the one property like this

    @property (nonatomic,strong) UIColor * myUIColor;

    Now When you can

    do this like

    myUIColor =[UIColor colorWithRed:1.000 green:0.500 blue:0.000 alpha:1.000]

    when you need CGColor

    myUIColor. CGColor