-1

你好朋友我是iOS开发的新手。我有一个与 NSTimer 相关的问题。我在我的视图控制器中使用 NSTimer。
计时器开始减少 UIButton 事件的值。当我转到另一个视图控制器时调用计时器后。然后计时器减少它工作正常的值。但是当我回到计时器视图时,计时器停止更新值意味着计时器不调用它的 @selector() 方法。当我回到计时器视图时如何调用值更新方法?

我的代码如下:

-(IBAction)btnStrDecPressed:(id)sender
{

    countDownlabel.text = [NSString stringWithFormat:@"%@:%@:%@", pickhour, pickmins, picksecs];
    secondsLeft=[pickhour intValue] * 3600;
    secondsLeft=secondsLeft + [pickmins intValue] * 60;
    secondsLeft=secondsLeft + [picksecs intValue];
    appdel.LeftSeconds=secondsLeft;
    NSLog(@"%d",appdel.LeftSeconds);


   if(timer==nil)
   {
       timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
   }
 }

-(void)updateCountdown
{
  int hours, minutes, seconds;

  hours = appdel.LeftSeconds / 3600;
  minutes = (appdel.LeftSeconds % 3600) / 60;
  seconds = (appdel.LeftSeconds %3600) % 60;
  appdel.LeftSeconds--;
  countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];

  if (appdel.LeftSeconds==0)
  {
      [[[UIAlertView alloc] initWithTitle:@"Restaurant" message:@"Timer Completed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
      [timer invalidate];
  }
}

其中 pickhour、pickmins、picksecs 是从 UIPickerview 获取的值。

4

3 回答 3

1

使用以下代码:

-(void)viewWillAppear:(BOOL)animated
{
    timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

-(void)updateCountdown
{
  NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
  int hours, minutes, seconds;
  if([def valueForKey:@"time"] != nil)
  {
     countDownlabel.text = [def valueForKey:@"time"];
  NSArray *arr = [countDownlabel.text componentsSeparatedByString:@":"];
  hours = [arr objectAtIndex:0];
  minutes = [arr objectAtIndex:1];
  seconds = [arr objectAtIndex:2];
  appdel.LeftSeconds--;
  }
  else{
  hours = appdel.LeftSeconds / 3600;
  minutes = (appdel.LeftSeconds % 3600) / 60;
  seconds = (appdel.LeftSeconds %3600) % 60;
  appdel.LeftSeconds--;
  }
  countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
  [def setValue:[NSString stringWithFormat:@"%@",countDownlabel.text] forKey:@"time"];
  if (appdel.LeftSeconds==0)
  {
      [[[UIAlertView alloc] initWithTitle:@"Restaurant" message:@"Timer Completed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
      [timer invalidate];
  }
}

(注意:使用 NSUserdefault 值来存储时间,当视图出现时,将获取默认存储值)

于 2013-08-02T09:44:31.130 回答
0

问题是每次您离开计时器视图控制器并返回时,您都会创建它的新实例。这就是为什么计时器每次都是 nil 并且每次启动计时器时它都会减少 1 秒。

我建议您将updateCountdown选择器和计时器移至 AppDelegate。

于 2013-08-02T10:51:08.353 回答
0

计时器一直在滴答作响,直到您的 [计时器无效] - 不仅仅是当您可以看到视图时。

您无法重新初始化它的原因是您没有完全重置计时器。尝试:

[timer invalidate];
timer = nil;
于 2013-08-02T09:47:24.930 回答