Any way to keep NSTimer running even when segue gets called?

If I have a running NSTimer and I want to navigate to a different screen, is there a way I can keep my NSTimer running from the original screen even when in the different screen?

Answered by QuinceyMorris in 252175022

In general, when you want to keep an object (a NSTimer instance in your case) alive independently of the lifetimes of other objects (whatever objects you're using to represent "screens"), you need to keep a reference somewhere else. Typically for this sort of thing, you can keep a reference in your application delegate object (which is an object whose behaviour you control, and which is always alive).


So, instead of making a timer property of (say) a view controller, put a timer property in the app delegate. The view controller, where it currently creates the timer, should first test whether the timer exists. If not, it can create it and store the reference in the app delegate property.

What action do you fire after timer has elapsed ?


What happens when you unwind segue ? Is timer active and uptodate ?


One idea would be to pass timer information in prepareForSegue and create a new timer in the VC where you have segued.

Accepted Answer

In general, when you want to keep an object (a NSTimer instance in your case) alive independently of the lifetimes of other objects (whatever objects you're using to represent "screens"), you need to keep a reference somewhere else. Typically for this sort of thing, you can keep a reference in your application delegate object (which is an object whose behaviour you control, and which is always alive).


So, instead of making a timer property of (say) a view controller, put a timer property in the app delegate. The view controller, where it currently creates the timer, should first test whether the timer exists. If not, it can create it and store the reference in the app delegate property.

I'm going to give this a try. Great idea.

Any way to keep NSTimer running even when segue gets called?
 
 
Q