Search code examples
iostimernstimernstimeinterval

How do i use NSTimer with navigation flow of application?


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.


Solution

  • 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];
        }
    }