Search code examples
iosuisearchbaruisearchbardelegate

Execute code once in SearchBar textDidChange delegate


I want to execute certain code (only once) when user enters three or more character in searchbar. I have used below code :

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

        if ([searchText length] >= 3) { 

         [self performSelector:@selector(searchBarSearchButtonClicked:) withObject:theSearchBar afterDelay:3.0];    
        }    
   }

The problem in using above code is it executes number of times greater than three. Eg. If five character is entered in searchbar then it executes for three times (desired only once).

How to achieve this? Sure +1 for correct answer.


Solution

  • I found solution by using NSTimer. Below is snippet :

    - (void) searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
    
        [timer invalidate];
        timer = nil;    
        ...
    
        if ([searchText length] >= 3) { 
    
           timer = [NSTimer scheduledTimerWithTimeInterval: 3.0 target: self
                 selector: @selector(SearchBarProxyCall) userInfo:nil repeats: NO];   
        }
    }
    
    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
        [timer invalidate];
        timer = nil;
    
        ...
    }
    
    -(void)SearchBarProxyCall { 
        [self searchBarSearchButtonClicked:searchbar];
    }