Getting "NSRangeException" Exception

I get an exception for substringWithRange: the range below the method.

I have a text box with editing disabled.

I use the text box to select text only. when I select text for the first time without exception, but when I click on it a second time.

Exception: "NSRangeException", reason: "* - [NSCFString substringWithRange:]: range or index out of bounds."

- (void)textViewDidChangeSelection:(UITextView *)textView {

NSRange range = [tv selectedRange];
str = [tv.text substringWithRange:range];
}
+3
source share
1 answer

I checked your example. Sometimes you retrieve the undefined range (2147483647, 0). So check this out to avoid crashes:

- (void)textViewDidChangeSelection:(UITextView *)textView {
    NSRange range = [textView selectedRange];
    if(range.length == 0 || range.location > textView.text.length)
        return;

    NSString *str = [textView.text substringWithRange:range];
}
+2
source

All Articles