NSRange崩溃的应用程序 [英] NSRange crashing app
问题描述
我遇到NSRange的问题,导致我的应用在textview为空时崩溃。我正在使用一个自定义键盘上有一个退格键,它在这里调用此代码...
I have an issue with NSRange that is causing my app to crash when textview is empty. I am using a custom keyboard that has a backspace button on it and it calls this code here...
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的开头并且没有更多的字符时,我得到异常并崩溃...
If I have text in the textview this works perfectly for removing one character at a time however when I get to the beginning of the textview and there are no more characters, I get the exception and crash...
*** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'
我的目标是让退格功能停止。我明白为什么它会崩溃,但我不知道如何解决它。我试过没有运气对NSNotFound进行评估。
My goal is to have the backspace function stop. I understand why it is crashing but I don't know how to resolve it. I have tried evaluating it against NSNotFound without luck.
任何想法都会非常感激!
Any ideas would be much appreciated!
推荐答案
你应该检查字段中是否有文字,即:
You should check that there is text in the field, ie:
if ( myChart.text.length > 0 )
并检查以确保您没有尝试访问位置-1 :
and also check to make sure you aren't trying to access location -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);
}
}
这篇关于NSRange崩溃的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!