Ios – Display a timer for an iOS app that persists between view controllers

cocoa-touchiosnstimerobjective c

I've been trying to get a timer to show at the bottom left corner of my app by using an NSTimer, and making the "elapsed time" show as UILabel on the bottom left corner but it hasn't been working for me.

-(void)viewDidLoad
{
    NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}

-(void)aTime
{
    NSLog(@"....Update Function Called....");

    static int i = 1;

    Label.text = [NSString stringWithFormat:@"%d",i];

    i++;
}

The timer actually works but I can't get it to be triggered by a button. I'm trying to get the timer to continue and not restart at 1 when it enters to the next storyboard/xib file.

Best Answer

For implementing the timer action on the button press, you need to write it on a IBAction method like:

- (IBAction) buttonPress
{
    NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}

For storing the previous value, you can use NSUserDefaults or a SQLite database. For this purpose I'll suggest NSUserDefaults.

Change the aTime method like:

-(void)aTime
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    id obj = [standardUserDefaults objectForKey:@"TimerValue"];
    int i = 0;

    if(obj != nil)
    {
        i = [obj intValue];
    }

    Label.text = [NSString stringWithFormat:@"%d",i];
    i++;

    [standardUserDefaults setObject:[NSNumber numberWithInt:i] forKey:@"TimerValue"];
    [standardUserDefaults synchronize];
}
Related Topic