0

Today I received a random crash on the isEqualToString method used with text property of UISearchBar. The crash was reported on Crashlytics.

Following is the code snippet.

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if( [searchBar.text isEqualToString:@" "] )
    {
        [searchBar setText:@""];
    }
    if ( searchBar.text.length >= 2 )
    {
        [self performSelectorInBackground:@selector(searchForKeyword:) withObject:searchBar.text];
    }
}

-(void)searchForKeyword:(NSString *)keyword
{
    if ([keyword isEqualToString:searchBar.text])
    {
        //Search for keyword
    }
}

The crash says

Fatal Exception: `NSRangeException`
*** -[NSBigMutableString _newBigSubstringWithRange:wantsMutable:zone:]: Range {0, 4} out of bounds; string length 3

I have tried debugging line of code that is causing the crash but with no success. It is just randomly crashing. Thanks in advance

Anoop Nyati
  • 339
  • 2
  • 11

1 Answers1

1

The error is caused by that:You set the search bar text in

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText   

You should use the method below instead of what you use.

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0); // called before text changes
childrenOurFuture
  • 1,889
  • 2
  • 14
  • 23