7

I have a repeated timer with interval of 1/4 second. I am initializing it like this:

[NSTimer scheduledTimerWithTimeInterval:0.25 
                                 target:self 
                               selector:@selector(toggleCams) 
                               userInfo:nil 
                                repeats:YES];

Does this happen synchronously? In other words, am I guaranteed that another method in the same class will not be called at the same time toggleCams is called?

0xSina
  • 20,973
  • 34
  • 136
  • 253

1 Answers1

19

The NSTimers actually just periodically fire events into the enclosing NSRunLoop, which each thread has (or should have). So, if you have a child (or background) process running in a different thread, the NSTimers will fire against that thread's NSRunLoop instead of the application's main NSRunLoop.

Saurabh
  • 22,743
  • 12
  • 84
  • 133
  • and what about the invalidate method? suppose two threads at same moment of time are invoking the invalidate method. Or one thread is checking whether is valid and another thread is invoking the invalidate method.Here is what Apple says: "Special Considerations You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly." – Nikita May 25 '18 at 19:47
  • "...you should always call the invalidate() method from the same thread on which the timer was installed." source https://developer.apple.com/documentation/foundation/timer – Awesomeness Aug 11 '20 at 13:06