开发者

UISearchDisplayController and images lazy loading

开发者 https://www.devze.com 2023-04-02 10:45 出处:网络
I am using a UITableView in combination with a UISearchDisplayController to do search on the table data array.

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 c开发者_如何学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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号