2012-05-02 75 views
-1

我是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

您確定傳遞給您的方法的hexColor字符串長度至少爲六個字符嗎? – jonkroll

+0

字符串是什麼樣的?你有沒有嘗試過記錄它或在調試器中檢查它? –

回答

2

也許十六進制字符串不是6個字符或更多?

您可以在方法開始時添加完整性檢查以捕獲該方案。

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

    // ... 
} 
+0

太好了我的錯誤解決非常感謝 – user1369211