Search code examples
objective-ciostimernsdatestopwatch

I have a NSDate, how do i show a stopwatch that auto updates showing a timer?


I have a NSDate variable. From that variable, how I can show a stopwatch that continuously updates in the view?

I've tried [NSTimer scheduledTimerWithTimeInterval] but can't get it working but also doubt that is the ideal way to do that.


Solution

  • Try this

    - (void)updateTimer
    {
        static NSInteger counter = 0;
        [stopWatchLabel setText:[NSString stringWithFormat:@"Counter: %i", counter++]];
    }
    
    - (IBAction)onStartPressed:(id)sender {
        startDate = [[NSDate date]retain];
    
        // Create the stop watch timer that fires every 10 ms
        stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
                                                          target:self
                                                        selector:@selector(updateTimer)
                                                        userInfo:nil
                                                         repeats:YES];
    }
    

    You have to connect the IBAction to a button, and the stopWatchLabel to a UILabel in the interface builder.

    Found on: http://www.apptite.be/tutorial_ios_stopwatch.php