As far as I know, there is no way to prevent the OS from being squeezed out of the thread and restarting in its place. The best you can do is synchronize access. But while reading your code, I do the following:
- - internal state variable.
- You want the timer not to be scheduled during a shutdown.
- You want to avoid a trip when scheduling a timer.
I think it's best to avoid synchronization whenever possible. Fortunately, you are using NSTimer, which will make things trivial.
NSTimer does NOT start in the background thread, but on NSRunLoop and probably in the main run loop, like your dealloc . Timers are event sources for the trigger cycle. When they fire, they trigger an event that, in turn, triggers your code when it is processed. Since the run loops process one event at a time, this means that the code in your scheduled timer and the code in your dealloc are fully executed before the other can work. It also means that you do not need any special synchronization mechanism.
- (void) dealloc { // ... if (_connected) { [_pingTimer invalidate]; if (_socket != -1) close(_socket); } // ... [super dealloc]; }
Note. I prefer to use state variables directly when I can, unless setters have other side effects. It also makes no sense to set state variables in dealloc simply because the object will disappear after the method call completes.
source share