NSTimer倒计时问题

时间:2014-03-15 22:13:07

标签: ios iphone nstimer

您好我最近在我的应用程序中添加了一个计时器,所以当用户点击气球时它会启动计时器,但我也有一个连接到该按钮的点击计数器。因此,当我按下气球多次点击计数器工作时,我的问题也是如此,但是当开始点击更快时,计时器会卡在一个循环中,当我停止点击它时,它会在零点之前倒数到负值,真的很快< / p>

我该如何解决这个问题?

    - (IBAction)yourbuttonClicked1:(UIButton *)sender
    {


   //start a background sound
   NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"tap" ofType:   
    @"wav"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];
   myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil ];
  [myAudioPlayer play];

     //for Switch view
    ViewController2 *nextView = [[ViewController2 alloc] initWithNibName:@"ViewController" 
  bundle: nil];
  [self.navigationController pushViewController:nextView animated:YES];

这是定时器代码的位置,我认为它可能与分接计数器冲突?

  myTime = 60;
  countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self    
 selector:@selector(countDown) userInfo:nil repeats:YES];

 }



 -(void)countDown {

myTime = myTime;
countdownLabel.text = [NSString stringWithFormat:@"%i", myTime];

if (myTime == 0) {

    [countdownTimer invalidate];

  }


 }

这是定时器代码结束的地方!

  - (void) saveNumberOfTaps:(int)numberOfTaps {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:numberOfTaps]   
 forKey:@"numberOfTaps"];
NSLog(@"Saved numberOfTaps: %i", numberOfTaps);
}



 - (int) getNumberOfTaps {
if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"numberOfTaps"] intValue]) {
    int numberOfTaps = [[[NSUserDefaults standardUserDefaults]   
   objectForKey:@"numberOfTaps"] intValue];
    NSLog(@"Getting numberOfTaps: %i", numberOfTaps);
    return numberOfTaps;
}
else {
    NSLog(@"No taps saved yet");
    return 0;

    }
 }

2 个答案:

答案 0 :(得分:0)

检查你的-countDown方法:

myTime = myTime;

这是错字吗?

答案 1 :(得分:0)

尝试以这种方式修改计时器初始化:

 myTime = 60;

[countdownTimer invalidate];
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self    
 selector:@selector(countDown) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:countdownTimer forMode:NSRunLoopCommonModes];