2012-06-26 36 views
0

我有NSRange一個問題,導致我的應用程序崩潰時的TextView是空的。我使用的是上有一個退格按鍵的自定義鍵盤,它要求在這份代碼...NSRange崩潰的應用程序

if ([self.myChart isFirstResponder]) { 
    NSRange currentRange = myChart.selectedRange; 
    if (currentRange.length == 0) { 
     currentRange.location--; 
     currentRange.length++; 
    } 
    myChart.text = [myChart.text stringByReplacingCharactersInRange:currentRange withString:[NSString string]]; 
    currentRange.length = 0; 
    myChart.selectedRange = currentRange; 

    NSLog(@"%d", NSNotFound); 
} 

如果我有這完全適用於在同一時間但是,當我得到消除一個字符TextView的文本到的TextView的開始,沒有更多的文字,我得到的異常和崩潰......

*** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds' 

我的目標是有退格功能停止。我明白爲什麼它會崩潰,但我不知道如何解決它。我曾試着對NSNotFound進行評估,但沒有運氣。

任何想法將不勝感激!

+0

,因爲你試圖訪問長度超過字符 – rishi

+0

@ rishi - 是的,我意識到這一點在我的文章中提到丹,丹幫助了我。謝謝。 – Dan

回答

4

您應檢查是否有在現場的文字,即:

if (myChart.text.length > 0) 

,並檢查,以確保你是不是在嘗試訪問位置-1:

if (currentRange.location >= 0) 

所以你代碼看起來像

if ([self.myChart isFirstResponder] && myChart.text.length > 0) { 
    NSRange currentRange = myChart.selectedRange; 
    if (currentRange.length == 0) { 
     currentRange.location--; 
     currentRange.length++; 
    } 
    if (currentRange.location >= 0) 
    { 
     myChart.text = [myChart.text stringByReplacingCharactersInRange:currentRange withString:[NSString string]]; 
     currentRange.length = 0; 
     myChart.selectedRange = currentRange; 

     NSLog(@"%d", NSNotFound); 
    } 
} 
+0

這是一個完美和優雅的修復,謝謝丹! – Dan