1

Is considered thread-safe to call setFireDate: from another thread than the one in which the timer is scheduled? I mean, I detach this function in a new thread:

-(void)CFRunLoopTest {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];

    runLoop = CFRunLoopGetCurrent();

    CFRunLoopAddTimer(runLoop, (CFRunLoopTimerRef)timer, kCFRunLoopCommonModes);

    CFRunLoopRun();
    [pool drain];
}

May I call [timer setFireDate:] from the main thread? I did not found anything in documentation that forbids it...

Erik B
  • 40,889
  • 25
  • 119
  • 135
Manlio
  • 10,768
  • 9
  • 50
  • 79

2 Answers2

3

A note from the NSTimer reference for setFireDate: method says

You could potentially call this method on a non-repeating timer that had not yet fired, although you should always do so from the thread to which the timer is attached to avoid potential race conditions.

Also see if the following Discussion helps.

visakh7
  • 26,380
  • 8
  • 55
  • 69
  • yes but it's talking about "a non-repeating timer that had not yet fired", i wonder if it's valid for all kind of timers... – Manlio May 26 '11 at 12:44
2

Why not run the timer on the main thread? I don't understand why you would need to run it in a separate thread. You could always have the timerFireMethod: spawn a new thread if it consumes a lot of time, Just run the appropriate method with performSelectorInBackground:withObject:.

EDIT: So the documentation actually says that it isn't thread safe to call[timer setFireDate:] from another thread. However, my advice is still valid.

Erik B
  • 40,889
  • 25
  • 119
  • 135