Search code examples
iosobjective-cnstimer

Reset button on NSTimer


I have an NSTimer and I need a reset button that resets the variable on screen and stops that timer until it is started agin by the start button. Here's some code:

@implementation TimeController

int timeTick = 0;


NSTimer *timer;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    labelTime.text = @"0";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)startTimer:(id)sender {
    [timer invalidate];
    timer= [NSTimer scheduledTimerWithTimeInterval:60.0 target:(self) selector:(@selector(tick)) userInfo:(nil) repeats:(YES)];
}

- (IBAction)resetTicktock:(id)sender {
    [timer invalidate];

}

-(void)tick{
    timeTick++;
    NSString *timeString = [[NSString alloc] initWithFormat:@"%d", timeTick];
    labelTime.text = timeString;



}


@end

Thanks in advance!


Solution

  • It looks like you have a function started already to stop the timer. Just reset the variable there.

    - (IBAction)resetTicktock:(id)sender {
        [timer invalidate];
        labelTime.text = @"0";
    }
    

    Link your button to this method in your storyboard for the action "Touch Up Inside".