Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer not firing

For the life of me, I cannot figure out why this NSTimer wont fire. here is all of the code that appears relevant (at least to me)

- (IBAction)connectClick:(id)sender
{
    if (connected)
    {
        NSLog(@"Disconnecting");
        [timer invalidate];
        timer = nil;
        connected = NO;
        [Connect setStringValue:@"Connect"];
        NSLog(@"Finished\n");
    }
    else
    {
        NSLog(@"Connecting");
        timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        //[timer fire]; tested this line. same results
        [Connect setStringValue:@"a"]; 
        connected = YES;
        NSLog(@"Finished\n");
    }
}

- (void)timerFireMethod:(NSTimer*)theTimer
{
    NSLog(@"Fireing event");
    //[self resetRequest];
    //[spinner startAnimation:nil];
    //[request startAsynchronous];
}

I have read the apple docs, and other questions, but I cannot figure it out. It does not even call timerDireMethod: once. I have heard this could be caused by different threads, but as far as I can tell, I am not using multiple threads.

All ideas welcome.

like image 781
Adam Schiavone Avatar asked Feb 19 '12 05:02

Adam Schiavone


1 Answers

From NSTimer documentation for Mac OS X:

You must add the new timer to a run loop, using addTimer:forMode:. Then, after seconds seconds have elapsed, the timer fires, sending the message aSelector to target. (If the timer is configured to repeat, there is no need to subsequently re-add the timer to the run loop.)

Personally, I typically use +[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]

Also note that if you call this method on a background thread, or in a block operation that runs in a background queue, the NSTimer gets destroyed when the background thread does. So be sure you are running it on the main thread or in the main queue if appropriate for your situation.

like image 50
bneely Avatar answered Oct 14 '22 03:10

bneely