Domanda

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];
}
È stato utile?

Soluzione

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];
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top