我是iPhone的初学者,我得到了如下所示的运行时错误。当我在getColor方法中传递对象“textView.textColor = [self getColor:appDelegate.pickcolor];”我收到了错误
由于未捕获的异常'NSRangeException'而终止应用程序,原因:' - [__ NSCFConstantString substringWithRange:]:范围或索引越界'
- (UIColor *) getColor: (NSString *) hexColor
{
//NSLog(@"Calling Getcolor..");
unsigned int red, green, blue;
NSRange range;
range.length = 2;
range.location = 0;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
//NSLog(@"\n\tRed :%d\n",red);
range.location = 2;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
//NSLog(@"\n\tgreen :%d\n",green);
range.location = 4;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
//NSLog(@"\n\tblue :%d\n",blue);
return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green/255.0f) blue:(float)(blue/255.0f) alpha:1.0f];
}
提出任何建议和解决方案
答案 0 :(得分:2)
也许十六进制字符串不是6个字符或更多?
您可以在方法开头添加健全性检查以捕获该方案。
- (UIColor *) getColor: (NSString *) hexColor
{
if ([hexColor length] < 6)
return nil;
// ...
}