Jonny Vu
Jonny Vu

Reputation: 1428

Stop immediately NSTimer

I'm trying to stop my NSTimer (no repeats) immediately but i can't. my NSTimer do the following code:

-(void)timerAction:(NSTimer*)timer{
    dispatch_queue_t serverDelaySimulationThread = dispatch_queue_create("com.xxx.serverDelay", nil);
    dispatch_async(serverDelaySimulationThread, ^{
        [NSThread sleepForTimeInterval:2.0];
        dispatch_async(dispatch_get_main_queue(), ^{
            //CALL WEBSERVICE RESPONSE IN HERE
        });
    });
}

Each time textField Did Change, i will invalidate NSTimer and recreate NSTimer!! All i want to execute a request to WEBSERVICES if the Delay time between 2 times user typing characters bigger than 2s. My code is following

-(void) textFieldDidChange:(id)sender{
    [MyTimer invalidate];
    MyTimer = nil;
    MyTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(timerAction:) userInfo:nil repeats:NO];
}

But, when i quickly type "ABCD" -> 2s after that, 4 webservices was called. How can i stop NSTimer while it unfinished

Tks for advance!

Upvotes: 0

Views: 198

Answers (3)

mak
mak

Reputation: 1183

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    [myTimer invalidate];
    myTimer = nil;
    myTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self    selector:@selector(timerFired) userInfo:nil repeats:NO];
    return YES;
}

This worked for me.

Upvotes: 2

Hussain Shabbir
Hussain Shabbir

Reputation: 14995

The problem is you are implementing textdidchange delegate. So how many times you type text. It will get called. SO inside that you have written four letters. So definitely your NSTimer is calling four times your web service. I would suggest better to use - (void)controlTextDidEndEditing:(NSNotification *)aNotification So that whenever you enter or tabb out your webservice will called.

Upvotes: 0

Josip B.
Josip B.

Reputation: 2464

Your timer timeInterval is set to 0. So each time you type your timer fires. Change your code to look like this

MyTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
    target:self selector:@selector(timerAction:) userInfo:nil repeats:NO];

And it should work :)

Upvotes: 1

Related Questions