NSTimer problem

后端 未结 2 490
野的像风
野的像风 2020-12-03 20:32

So I am trying to set up a basic timer but I am failing miserably. Basically all I want is to start a 60 second timer when the user clicks a button, and to update a label wi

2条回答
  •  情书的邮戳
    2020-12-03 20:36

    Ok, well for starters, check this out if you haven't already: Official Apple Docs about Using Timers

    Based on your description, you probably want code that looks something like this. I've made some assumptions regarding behavior, but you can suit to taste.

    This example assumes that you want to hold on to a reference to the timer so that you could pause it or something. If this is not the case, you could modify the handleTimerTick method so that it takes an NSTimer* as an argument and use this for invalidating the timer once it has expired.

    @interface MyController : UIViewController
    {
      UILabel * theLabel;
    
      @private
      NSTimer * countdownTimer;
      NSUInteger remainingTicks;
    }
    
    @property (nonatomic, retain) IBOutlet UILabel * theLabel;
    
    -(IBAction)doCountdown: (id)sender;
    
    -(void)handleTimerTick;
    
    -(void)updateLabel;
    
    @end
    
    @implementation MyController
    @synthesize theLabel;
    
    // { your own lifecycle code here.... }
    
    -(IBAction)doCountdown: (id)sender
    {
      if (countdownTimer)
        return;
    
    
      remainingTicks = 60;
      [self updateLabel];
    
      countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(handleTimerTick) userInfo: nil repeats: YES];
    }
    
    -(void)handleTimerTick
    {
      remainingTicks--;
      [self updateLabel];
    
      if (remainingTicks <= 0) {
        [countdownTimer invalidate];
        countdownTimer = nil;
      }
    }
    
    -(void)updateLabel
    {
      theLabel.text = [[NSNumber numberWithUnsignedInt: remainingTicks] stringValue];
    }
    
    
    @end
    

提交回复
热议问题