"[NSBigMutableString substringWithRange:]: Range {0, 10} out of bounds; string length 9" error with Undo
Asked Answered
G

1

7

My app crashes when I try to do undo on UISearchBar. In my app I have code to prevent entering a '%' sign on the search bar and for doing this it replaces a % to @"" in textDidChange method as below:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
   self.searchBar.text = [searchText stringByReplacingOccurrencesOfString:@"%" withString:@""];
}

So if I type text "abc%xyz", the final text visible on search bar would be 'abcxyz'. No when I click undo, I see 'xyz' gets cleared and I still see 'abc' on the search bar instead of clearing 'abcxyz' all at one go.

Now if I click undo again to clear 'abc' my app crashes with [NSBigMutableString substringWithRange:]: Range out of bounds error.

I am assuming that even though '%' gets replaced by @"", the undo manager might still be holding it and hence the range is going out of bounds.

I tried [searchBar.undoManager removeAllActions]; in textDidChange after I replace % with @"", but it didn't help. Here is the code:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
    {
       self.searchBar.text = [searchText stringByReplacingOccurrencesOfString:@"%" withString:@""];
      [searchBar.undoManager removeAllActions];
    }

Question: Anybody faced similar issue before? How do I handle the undo?

Gonion answered 3/4, 2014 at 17:51 Comment(1)
Though removaAllActions worked for me. We finally opted to just turn off shake to undo for our app.Salicaceous
S
0

You should be using this delegate method instead:

        - (BOOL)searchBar:(UISearchBar *)searchBar
  shouldChangeTextInRange:(NSRange)range
          replacementText:(NSString *)text

And just return NO in case the replacementText is equal to "%". This will prevent the user from using it in the first place as it won't update the textfield, which should fix the undo issue you're having.

Solution

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"%"]) {
        return NO;
    }

    return YES;
}
Sphericity answered 24/11, 2015 at 8:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.