Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Exception 'NSRangeException'

I am getting Exception for substringWithRange:range in below method.

I am having textview with editing disabled.

i am using textfield only for text selection. when i am selecting text for firs time no exception but when i press for second time it throughs.

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

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

NSRange range = [tv selectedRange];
str = [tv.text substringWithRange:range];
}
like image 274
iosDev Avatar asked May 23 '26 20:05

iosDev


1 Answers

I've checked your example. Sometimes you retrieve an undefined range like (2147483647, 0). So, check it 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];
}
like image 140
beryllium Avatar answered May 26 '26 15:05

beryllium



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!