NSTimer没有调用值更新方法

时间:2013-08-02 09:06:52

标签: iphone ios nstimer ios5 nstimeinterval

朋友您好我是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的值。

3 个答案:

答案 0 :(得分: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值存储时间以及视图显示时将提取默认存储值)

答案 1 :(得分:0)

计时器一直在滴答作响,直到你的[计时器无效] - 而不仅仅是你能看到视图。

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

[timer invalidate];
timer = nil;

答案 2 :(得分:0)

问题在于,每次离开计时器视图控制器并返回时,都会创建一个新的实例。这就是为什么定时器每次都是零的原因,每次启动定时器时它都会减少1秒。

我建议你将updateCountdown选择器和计时器移动到AppDelegate。