Manlio
Manlio

Reputation: 10865

NSTimer setFireDate

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...

Upvotes: 1

Views: 1551

Answers (2)

Erik B
Erik B

Reputation: 42584

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.

Upvotes: 2

visakh7
visakh7

Reputation: 26400

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.

Upvotes: 3

Related Questions