“[NSBigMutableString substringWithRange:]: Range {0, 10} out of bounds; string length 9” error with Undo

依然范特西╮ 提交于 2019-11-28 07:36:40

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/22845277/nsbigmutablestring-substringwithrange-range-0-10-out-of-bounds-string-l

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