Dan
Dan

Reputation: 398

NSRange crashing app

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);
}

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'

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!

Upvotes: 0

Views: 4234

Answers (1)

Dan F
Dan F

Reputation: 17732

You should check that there is text in the field, ie:

if ( myChart.text.length > 0 )

and also check to make sure you aren't trying to access location -1:

if ( currentRange.location >= 0 )

So your code looks something like

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);
    }
}

Upvotes: 4

Related Questions