Getting Exception 'NSRangeException'

半世苍凉 提交于 2019-12-12 13:54:09

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/10104212/getting-exception-nsrangeexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!