Ios UIColor-getRed:…-引发异常

Ios UIColor-getRed:…-引发异常,ios,ios4,Ios,Ios4,我有以下测试代码: CGFloat endRed, endGreen, endBlue, endAlpha; [[UIColor greenColor] getRed:&endRed green:&endGreen blue:&endBlue alpha:&endAlpha]; 我为UIView类调用的内部drawRect方法。 此代码异常失败 2011-11-06 02:29:28.671 Chartous[13457:b303] -[UICachedDev

我有以下测试代码:

CGFloat endRed, endGreen, endBlue, endAlpha;

[[UIColor greenColor] getRed:&endRed green:&endGreen blue:&endBlue alpha:&endAlpha];
我为UIView类调用的内部drawRect方法。 此代码异常失败

2011-11-06 02:29:28.671 Chartous[13457:b303] -[UICachedDeviceRGBColor getRed:green:blue:alpha:]: unrecognized selector sent to instance 0x4e7ea10
2011-11-06 02:29:28.673 Chartous[13457:b303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICachedDeviceRGBColor getRed:green:blue:alpha:]: unrecognized selector sent to instance 0x4e7ea10'
这里怎么了

尝试另一种方法:

const CGFloat* components = CGColorGetComponents([[UIColor greenColor] CGColor]);
CGFloat red = components[0];
CGFloat green = components[1];
CGFloat blue = components[2];
CGFloat alpha = CGColorGetAlpha([[UIColor greenColor] CGColor]);

此方法仅在ios5及更高版本中可用。您是否在模拟器或设备的早期iOS版本上运行它?考虑到你的问题,我想是这样的

在单调颜色的情况下,组件的数量是2,因此您需要再次检查

例如。 [UIColor whitecolor]只有两个alpha和颜色组件

size_t num = CGColorGetNumberOfComponents(cgPrevColor);
CGFloat r,g,b;
if(num==2) {
    r = g = b = components[0];
} else {
    r = components[0];
    g = components[1];
    b = components[2];            
}

@odyodyodys——现在就唠叨一个被接受的答案还为时过早,这个问题只有45分钟的时间,而且自从两个最新答案发布后,op甚至还没有出现在网站上。是的,这确实是个问题。我更新到iOS5,一切都进行得很顺利。它应该是
CGColor
而不是
CGColor
如果有人得到实例方法-“CGColor”没有找到,我想知道为什么,如果你的颜色来自[UIColor whiteColor]类方法,这个代码会给你错误的R、G、B值,如果你重新组合它,它将是黄色而不是白色。我注意到,在这个例子中,CGColorGetNumberOfComponents(cgColor)给出了2!这很重要,因为您需要4个组件。如果以后需要获取组件,我想应该避免使用[UIColor whiteColor]。@krafter或者可以避免使用whiteColor并使用组件组装它(这很糟糕)@odyodyodys-从组件组装也很好,我想:const CGFloat components[4]={0.0,0.0,0.0,1.0};UIColor*whiteColor=[UIColor-colorWithCGColor:CGColorCreate(CGColorSpaceCreateDeviceRGB(),components)];