-1

I am beginner of iPhone and I got the runtime error shown below. When I pass the object in the getColor method "textView.textColor=[self getColor:appDelegate.pickcolor];" I get the error

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFConstantString substringWithRange:]: Range or index out of bounds'

- (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];
}

Give any suggestion and solution

THelper
  • 15,333
  • 6
  • 64
  • 104
  • Are you certain that the hexColor string you are passing to your method is at least six characters long? – jonkroll May 02 '12 at 06:00
  • What does the string look like? Have you tried logging it or inspecting it int the debugger? – jscs May 02 '12 at 06:12

1 Answers1

2

Maybe the hex string is not 6 characters or more?

You can add a sanity check at the start of the method to catch that scenario.

- (UIColor *) getColor: (NSString *) hexColor
{
    if ([hexColor length] < 6)
        return nil;

    // ...
}
Morten Fast
  • 6,322
  • 27
  • 36