NSTimer无法正常工作

时间:2013-07-31 08:57:57

标签: iphone timer nstimer countdown

我是iOS开发的新手,所以希望你能帮到我!我现在正在使用Xcode5-DP4而且我的代码没有正常工作(虽然它之前工作正常)。从点击按钮开始倒计时2:00(分:秒):

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;

    }
}

问题: - 定时器计数太快,不使用整秒(标签在0.5秒后和1.5秒后改变,依此类推......) - 计时器继续计数到负范围......

我希望你能帮助我=)。

提前谢谢,安德烈!

1 个答案:

答案 0 :(得分:0)

NSTimer有时在给定的时间间隔内无效。所以,我找到了一个解决方案,将下面的代码放在NSTimer对象

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

这可以解决您的问题。