0

I implemented a customized textview based on UITextView, trying to listen the text change event. So I implemented the UITextView's delegate:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    //It crashes!
    NSString *result = [textView.text stringByReplacingCharactersInRange:range withString:text];

    return YES;
}

In iOS 5 and iOS 6,the above code works fine. But in iOS 4.3, it crashes with the exception ***-[NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds. I printed all the variable values, found in iOS 4.3, sometimes the range is out of bound indeed: textView.text.length is 111, but the range is 113,0. What's wrong with my code? Thanks!

Hang
  • 469
  • 1
  • 4
  • 18
  • NSString *result = [[textView.text stringByReplacingCharactersInRange:range withString:text]copy]; try this instead of NSString *result = [textView.text stringByReplacingCharactersInRange:range withString:text]; – Sudha Tiwari Feb 04 '13 at 03:55
  • @Sudha Thanks! But it still crashes. And I think the crash came from the `Range or index out of bounds`. – Hang Feb 04 '13 at 04:04
  • get your textview.text in new string and pass that string in your result string........ I tried this and it works perfectly. – Sudha Tiwari Feb 04 '13 at 04:28
  • Are you calling `textView:shouldChangeTextInRange:replacementText` manually from anywhere in your project? This should work fine, unless it is manually called with incorrect paramaters. – lnafziger Feb 04 '13 at 04:37
  • @lnafziger Thanks for your reply! Yes, You are right, I did manually call the `textView:shouldChangeTextInRange:replacementText` in my code, and I forgot I had changed the range in the code. – Hang Feb 04 '13 at 05:55

1 Answers1

0

This method is automatically called whenever a change is made in a textview, and is very stable. My guess (as you confirmed in your comment above) is that you must be calling this method manually in your code, and providing an incorrect range.

lnafziger
  • 25,760
  • 8
  • 60
  • 101