1

I want to maintain timer with multiple UIViewControllers. Like, I am creating one timer in ViewController1 for 60 second interval. after 20 second, application navigates to ViewController2.(so 40 second is remaining to execute timer). After 20 second stay i come back to ViewController1, at this time timer should execute after 40 second of come back and then after it will execute after 60 second.

So how can I do this?

Thanks in advance.

Ajay Gabani
  • 1,168
  • 22
  • 38
  • It's pretty hard (atleast for me) to understand what you are trying to achieve. can you please elaborate ? – Guy S Feb 10 '15 at 11:14
  • It is much easier to maintain two separated timers for each UIViewController – Vladimir Berezkin Feb 10 '15 at 11:22
  • actually I don't want to use timer for ViewController2. I want to use timer for VC1 only but every 60 second of total appearance time on that VC1(like. First 20 sec and after getting back 40 sec = 60 sec). – Ajay Gabani Feb 10 '15 at 11:27

2 Answers2

0

Although it may be a solution with better practices, you can set the NSTimer inside your AppDelegate and make the AppDelegate manage segues to push or pop your UIViewControllers

aramusss
  • 2,391
  • 20
  • 30
  • Thank you, Yes that is one way. But I don't want to go with AppDelegate, Is there any way to Pause and Resume Timer with navigation? – Ajay Gabani Feb 10 '15 at 11:33
  • I would say the best practice may be to have a custom `UINavigationController` that controls the NSTimer and pushs/pops. Another solution could be passing the NSTimer through `- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender` but it seems really bad practice. – aramusss Feb 10 '15 at 11:37
0

If you want to use one item across several instances, try it with the singleton design pattern. But like it seems, you never navigate back from your VC1, so all obejects are still there.

On the base of How to Pause/Play NSTimer? you can change some parts to make it fitting your case.

- (void)stopTimer
{
    if( timer )
    {
        [timer invalidate];
        [timer release]; // if not ARC
        timer = nil;
    }
}

- (void)startTimer
{
    [self stopTimer];
    int interval = 1.;
    timer = [[NSTimer scheduledTimerWithTimeInterval:interval
                                              target:self
                                            selector:@selector(countUp)
                                            userInfo:nil repeats:YES] retain]; // retain if not ARC
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self timerStart];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self stopTimer];
    [super viewWillDisappear:animated];
}

-(void)countUp
{
    if(timePassed++ >= 60)  // defined in header
    {
        timePassed=0;
        [self myCustomEvent];
    }
}
Community
  • 1
  • 1
geo
  • 1,781
  • 1
  • 18
  • 30