"[NSBigMutableString substringWithRange:]: Range {0, 10} out of bounds, line length 9" error with cancellation

My application crashes when I try to cancel the UISearchBar . In my application, I have code to prevent the% sign from entering in the search bar, and for this it replaces the% to @ "" method in the textDidChange method, as shown below:

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

Therefore, if I type in the text "abc% xyz", the final text visible on the search bar will be "abcxyz". No, when I click the Cancel button, I see that "xyz" is cleared, and I still see "abc" in the search bar, instead of clearing "abcxyz" all at once.

Now, if I cancel the cancellation again to remove the 'abc', my application crashes with the error [NSBigMutableString substringWithRange:]: Range out of bounds .

I assume that although "%" is replaced with @, the cancellation manager may still hold it, and therefore the range is out of scope.

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

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

Question: Has anyone encountered a similar problem before? How do I cancel a cancellation?

+7
undo ios objective-c uisearchbar nsundomanager
source share
1 answer

Instead, you should use this delegate method:

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

And just return NO if replaceText is "%". This will not allow the user to use it in the first place, as it does not update the text field, which should fix the undo problem that you have.

Decision

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

All Articles