2
votes

I am using iOS7 i have a search bar. i am using textDidChange method to get each character and handling my code, I have clear "X button" when we have text. in previous versions when click on the clear button textDidChange method is called once and we used to handle the code there.

But in iOS7 this method is called twice when clicking on clear button , This behaviour i can see in Sample code also

  • (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
4
I'm facing the same issue. Can someone confirm whether this is a bug or did it work this way in the previous iOS versions too. Also, could someone tell me how to ignore one of the consecutive events? Thanks in advance. - Prathiba

4 Answers

4
votes

I just tried myself and it's true, the method is called twice with the exact same parameters. Reading the documentation it doesn't say anything about it, so it may be just a bug.

Can you ignore it?

3
votes

You can create a private property:

@property (strong, nonatomic) NSString *searchedText;

and use it to check for equality:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)newText{
    if(![self.searchedText isEqualToString:newText]){ 
        self.searchedText = [[NSString alloc] initWithString:newText];
        //Do your magic
    }
}
0
votes

I have the same issue, I solved it by creating a ivar... This worked for me because I reload my table after calling this and I reset textDidClear = NO; in my reloadTable method.

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (([searchText isEqualToString:@""]) && (textDidClear == NO))
    {
        textDidClear = YES;
        [_categoryManager loadCategoriesWithToken:nil];

    } else if (textDidClear == NO) {
        textDidClear = NO;
        [_productManager loadProductsFromSearch:searchText tokenIdent:nil];
    }
}
0
votes

When you are working in the simulator and you type with the keyboard of your computer in the search bar, sometimes is calling twice to the method

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)newText.

To avoid this problem you have to use the simulator keyboard. Looks like it is a simulator bug.