Search code examples
iosuicolor

Exception when getting CGColor from UIColor in iOS


I am trying to create custom buttons for my views. Everything works well except when rendering I am getting an exception being thrown regarding my colors. My class has 2 color properties:

@property (nonatomic, retain) UIColor* defaultBackground;
@property (nonatomic, retain) UIColor* clickedBackground;

One to represent the default rendering color and the other for when the user has it clicked. Inside my initWithFrame method I initialize the colors:

defaultBackground = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
clickedBackground = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];

This is all well and good until I get to the rendering where it throws an exception when getting the CGColor:

if((self.state & UIControlStateHighlighted) == 0)
    {
        CGContextSaveGState(context);
        CGContextSetFillColorWithColor(context, defaultBackground.CGColor); //Crashes on this line
        ...

Here is the exception that I am getting:

2012-04-13 10:19:51.005 -[__NSMallocBlock__ CGColor]: unrecognized selector sent to instance 0x7d94d20
2012-04-13 10:19:51.072 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSMallocBlock__ CGColor]: unrecognized selector sent to instance 0x7d94d20'

Any ideas would be greatly appreciated.


Solution

  • Change the two lines in your initWithFrame: as follows:

    self.defaultBackground = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    self.clickedBackground = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
    

    The problem is that assigning an autoreleased UIColor object directly to an ivar results in a dangling pointer to a released object. An alternative is:

    defaultBackground = [[UIColor alloc] initWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    clickedBackground = [[UIColor alloc] initWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];