Question

My app is crashing when I try to change the color of the text which is inside a button myButton.titleLabel.textColor.

If I do that the app does not crash but the color of the text keeps in blackColor:

[myButton setTitleColor:[UIColor colorWithRed:0.41 green:0.107 blue:0.252 alpha:1.0] forState:UIControlStateNormal];

If I do this other way the app crashes:

.m:

-(IBAction)buttonTapped:(id)sender {

    [myButton setTitleColor:myColor forState:UIControlStateNormal];

}

[...]

-(void) viewDidLoad {

    myColor = [UIColor colorWithRed:0.41 green:0.107 blue:0.252 alpha:1.0];

}

.h:

UIColor *myColor;

debugger output:

2013-04-20 18:23:45.625 myApp[6291:c07] -[NSShadow set]: unrecognized selector sent to instance 0x753bfd0
2013-04-20 18:23:45.627 myApp[6291:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSShadow set]: unrecognized selector sent to instance 0x753bfd0'
*** First throw call stack:
(0x15bb012 0x12c8e7e 0x16464bd 0x15aabbc 0x15aa94e 0x369c87 0x369f76 0x368cd9 0x36b098 0x25ce6e 0x126a3f 0x12652c 0x1269ba 0x1262b6 0x126994 0x11b0e2 0x11b15c 0x990bc 0x9a227 0x9a8e2 0x1583afe 0x1583a3d 0x15617c2 0x1560f44 0x1560e1b 0x261c7e3 0x261c668 0x20cffc 0x21c2 0x20f5)
libc++abi.dylib: terminate called throwing an exception
(lldb) 

How can I solve that? I want to use the second way (if possible).

Was it helpful?

Solution

The color object that you create with colorWithRed:green:blue:alpha: is autoreleased, so by the time buttonTapped: is called, the object has already been deallocated, so you have a pointer that points to garbage data (a dangling pointer).

You could either switch to using ARC (automatic reference counting), and/or create a retained property for myColor. That would look like this in your header:

@property (nonatomic, retain) UIColor *myColor;

Then, instead of setting the instance variable directly, use:

self.myColor = [UIColor colorWithRed:0.41 green:0.107 blue:0.252 alpha:1.0];

in viewDidLoad. If you don't use ARC, don't forget to release the color in dealloc:

- (void)dealloc
{
    [_myColor release];
    [super dealloc];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top