Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer - Why does scheduledTimerWithTimeInterval work, yet initWithFireDate doesn't?

Tags:

objective-c

This calls my selector repeatedly each 60 seconds as desired:

autoDeleteTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:[SimpleDB class] selector:@selector(autoDelete:) userInfo:nil repeats:YES];

This next line doesn't call it at all. Not initially nor after 60 seconds:

autoDeleteTimer = [[NSTimer alloc] initWithFireDate: [NSDate dateWithTimeIntervalSinceNow:1] interval:60 target:[SimpleDB class] selector:@selector(autoDelete:) userInfo:nil repeats:YES];

Can anyone explain why? Thanks.

like image 532
Aaron Bratcher Avatar asked Sep 17 '25 12:09

Aaron Bratcher


1 Answers

You need to add the second timer to the main loop:

[[NSRunLoop mainRunLoop] addTimer: autoDeleteTimer forMode:NSDefaultRunLoopMode];

From the documentation of the method:

- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

Return Value: The receiver, initialized such that, when added to a run loop, it will fire at date and then, if repeats is YES, every seconds after that.

You must add the new timer to a run loop, using addTimer:forMode:. Upon firing, the timer sends 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.)

NSTimer Apple Doc

like image 161
Antonio MG Avatar answered Sep 20 '25 03:09

Antonio MG