-3

Say I want to implement some fast searching. User enter some letters and and everytime the letter changes then my program will search the net to give search suggestions.

However, I do not want that function to be called more often than 3 seconds.

How would I do so?

I currently use a timer. Also the "search" the net for auto complete will be done on background so some multithreading issue will show up.

I'll post codes soon. But most answers are similar with mine.

Oh ya, the complexity is that if users type too fast the grabbing should still be done after 3 seconds. So not right away but still be done.

user4951
  • 32,206
  • 53
  • 172
  • 282

3 Answers3

2

When you detect the new letter just check how much time has passed:

NSDate *d = [NSDate date];

if( lastSearch == nil || [d timeIntervalSinceDate:lastSearch] > 3 )
{
    lastSearch = d;

    // Do your search ...

}

Declare lastSearch in your .h file like so:

NSDate *lastSearch;
Xavi Gil
  • 11,460
  • 4
  • 56
  • 71
1

You can create timer and check updates of your search string. Smth like

timer = [NSTimer timerWithTimeInterval:3.f target:self selector:@selector(update) userInfo:nil repeats:YES];

then just implement update method

-(void) update
{
    BOOL needToSearch = // check if there was changes in your search string
    if ( needToSearch )
    {
        // make new search
    }
}

just don't forget too invalidate your timer when you do not need it

Morion
  • 10,495
  • 1
  • 24
  • 33
0

Set it up so that when your timer expires, the search is performed, but whenever the user enters a character, reset the timer back to the delay amount.