5

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.

Adam Schiavone
  • 2,412
  • 3
  • 32
  • 65
  • possible duplicate of [NSTimer not firing](http://stackoverflow.com/questions/6752234/nstimer-not-firing) – Caleb Feb 19 '12 at 05:59
  • Is there some reason that you're using NSEventTrackingRunLoopMode instead of NSDefaultRunLoopMode? – Caleb Feb 19 '12 at 06:06
  • Sorry Its late here. I just noticed that and was going to add that to the question. but yes NSDefaultRunLoopMode worked. Sorry for confusing you. – Adam Schiavone Feb 19 '12 at 06:07
  • possible duplicate of [NSTimer Delegate Selection](http://stackoverflow.com/questions/9288965/nstimer-delegate-selection) – jscs Feb 19 '12 at 07:07

2 Answers2

9

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.

bneely
  • 9,083
  • 4
  • 38
  • 46
1

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.

Caleb
  • 124,013
  • 19
  • 183
  • 272