Adam Schiavone
Adam Schiavone

Reputation: 2452

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.

Upvotes: 5

Views: 3579

Answers (2)

bneely
bneely

Reputation: 9093

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.

Upvotes: 9

Caleb
Caleb

Reputation: 125037

Read the documentation for the method you're using, +timerWithTimeInterval:target:selector:userInfo:repeats::

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.

Upvotes: 1

Related Questions