Akshay Gajarlawar Akshay Gajarlawar - 24 days ago 6
Objective-C Question

Invalidate NSTimer with block which has not been fired yet : Objective-C

I've used NSTimer category to create timer with block from https://github.com/jivadevoe/NSTimer-Blocks. I'm trying to invalidate timer in one of my method before that timer get fired, but its not working. My code is as follows :

-(void)addQuestionView
{
if([resizeTimer isValid])
[resizeTimer invalidate];
.
.
.
.
.

[webView loadHTMLString:questionHtmlStr
baseURL:nil];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
resizeTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 block:^{

//calculating height based on content
//changing webView's contsraints


} repeats:NO];

.
//long process
//animation
.

}


As in above code, if addQuestionView method called 1st time, timer will set to run after 4 secs. If addQuestionView called immediately, say after 1 secs, I want resizeTimer to invalidate in order to avoid any misconduct in calculating height and changing constraints of webView. I checked this by NSLogging some values, its not getting invalidated, and getting called twice. Anybody have solution, then please help me.

Thanks !

Rob Rob
Answer

You should make sure you invalidate the prior timer (if any) before instantiating a new timer, e.g.:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if ([resizeTimer isValid])
        [resizeTimer invalidate];

    resizeTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 block:^{
        ...
    } repeats:NO];

    ....
}