Strange crash when I try to access to uibutton'

2019-08-27 03:12发布

问题:

I found another annoying bug with xcode 4.5 and sdk 6.0 : when I run the following code :

UIColor *newcolor = [UIColor colorWithCIColor:[CIColor colorWithString:@"1 1 1 1"]];
[button setTitleColor:newcolor forState:UIControlStateNormal];
UILabel *lbl = selectedbutton.titleLabel;

It always fail with the error :

-[UICIColor colorSpaceName]: unrecognized selector sent to instance 0xa9864f0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICIColor colorSpaceName]: unrecognized selector sent to instance 0xa9864f0'
*** First throw call stack: [...] 
libc++abi.dylib: terminate called throwing an exception

回答1:

I found a workaround : before using my colorWithCIColor, I made a copy of it with :

newcolor = [UIColor colorWithCGColor:newcolor.CGColor];

and it solves the crash. Strange, anyway



回答2:

I was in the same situation as you where I had a string of the constituent values of the RGB UIColor

Although using CIColor colorWithString: is much more compact to get rid of the error I converted it manually:

NSArray * colorParts = [color componentsSeparatedByString: @" "];

CGFloat red = [[colorParts objectAtIndex:0] floatValue];
CGFloat green = [[colorParts objectAtIndex:1] floatValue];
CGFloat blue = [[colorParts objectAtIndex:2] floatValue];
CGFloat alpha = [[colorParts objectAtIndex:3] floatValue];

UIColor * newColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

[button setTitleColor:newcolor forState:UIControlStateNormal];

This certainly isn't the most elegant way of doing it but is a good fix if this suddenly becomes an issue after an update.