Search code examples
iphonetimernstimercountdown

NSTimer does not work properly


I'm pretty new to iOS Development so hopefully you can help me! I'm using Xcode5-DP4 right now and my code isn't properly working (although it worked fine before). There is a countdown 2:00 (min:sec) starting by tapping a button:

FirstViewController.h:

@interface FirstViewController : UIViewController {
     IBOutlet UILabel *countdownLabel;
     IBOutlet UIButton *countdownStart;
     NSTimer *countdownTimer;
     int secondsCount;
}

-(IBAction)alert;
-(void)delay;

FirstViewController.m:

UIAlertView *alert;

-(void)delay {
    [alert show];
 }


 -(IBAction)alert{
     alert = [[UIAlertView alloc]
          initWithTitle:@"Die Zeit ist um!"
          message:@"Du darfst das Zähneputzen nun beenden, aber vergiss nicht, noch mehr für deine Mundhygiene zu tun."
          delegate:self
          cancelButtonTitle:@"OK"
          otherButtonTitles:nil];

     [self performSelector:@selector(delay) withObject:nil afterDelay:120.0];
 }


 - (IBAction)zaehneputzen:(id)sender {

    [self setTimer];
 }


 - (void) setTimer {

    secondsCount = 120;
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:(self) selector:@selector(timerRun) userInfo:(nil)
    repeats:(YES)];
 }

 - (void) timerRun {

    secondsCount = secondsCount-1;
    int minutes = secondsCount / 60;
    int seconds = secondsCount - (minutes * 60);

    NSString *timerOutput = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
    countdownLabel.text = timerOutput;

    if(secondsCount == 0){

       [countdownTimer invalidate];
       countdownTimer = nil;

    }
}

The problems: - Timer is counting too fast and does not use full seconds (the label is changing after 0.5sec and after 1.5sec and so on...) - the timer keeps on counting into a negative range...

I hope you can help me =).

Thanks in advance, Andrea!


Solution

  • NSTimer sometimes doesn't work with given time interval. So, I found one solution that put the below line code after your NSTimer object

    [[NSRunLoop currentRunLoop] addTimer:yourtimer forMode:NSRunLoopCommonModes];
    

    This may solve your problem.