问题描述:

I am using a UITableView in combination with a UISearchDisplayController to do search on the table data array.

for each row shown an image is fetched from the network and cached locally.

the problem is when the user types a search term, each key triggers a call to shouldReloadTableForSearchString which I use to start the online image fetch. If the user types fast it will create several network requests, by the time the network fetch is completed, the row that triggered it might not exist anymore since the search was changed.

I figured I need to wait until the user stops typing before making the network request, but could not yet find a way to do so with UISearchBar and UITableView..

any ideas?

网友答案:

You need to setup a timer upon every key stroke. Lets say you assume that a user has stopped typing if the last key stroke was received 1 second ago. Instead of returning YES from shouldReloadTableForSearchString:, you should schedule a timer. If another key stroke is received before 1 second elapses, invalidate the timer and reset it.

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    if(myTimer) //a timer is already scheduled. Invalidate it.
    {
        [myTimer invalidate]; //myTimer is an iVar
        myTimer = nil;
    }

    myTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:1] interval:0 target:self selector:@selector(search:) userInfo:searchString repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];          
    return NO;
} 

- (void)search:(NSTimer*)theTimer
{
      //make network request here
}

Call [self.searchDisplayController.searchResultsTableView reloadData]; when the response from the network call is received.

相关阅读:
Top