How to stop NSTimer at a specific point?

2019-08-01 09:10发布

问题:

I've created a simple button game that gives the user a point with every tap of the button. The button randomly appears on screen every 1.5 seconds. I want the game to end after 30 seconds or after 20 random button pop ups. I've been using the code below to have the button randomly pop-up on the screen:

timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self
         selector:@selector(moveButton:) 
         userInfo:nil 
         repeats:YES];

I've declared the timer in the header file:

NSTimer *timer;
@property (nonatomic, retain) NSTimer *timer;

I've read Apple Docs on Using Timers but fail to fully understand it. I thought maybe I could use:

- (void)countedTimerFireMethod:(NSTimer *)timer{
  count ++;
  if(count > 20){
     [self.timer invalidate];
     self.timer = nil;

But it does not work properly. What am I doing wrong? I'm new to objective-C so I'm not that familiar with how things work.

回答1:

The problem is on your timer method you are passing moveButton method but in below method where you are stopping the timer that method name is different so try this:-

  self.timer = [NSTimer     
  scheduledTimerWithTimeInterval: 1.5 target:self
     selector:@selector(moveButton:) 
     userInfo:nil 
     repeats:YES];

//just change the method name below

 - (void)moveButton:(NSTimer *)timer{
  count ++;
  if(count > 20){
    [self.timer invalidate];
    self.timer = nil;}


回答2:

If you are using new version of Xcode then you don not need to declare

NSTimer *timer;

and when scheduling a timer you can use

self.timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self
         selector:@selector(moveButton:) 
         userInfo:nil 
         repeats:YES]

instead of

timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self
         selector:@selector(moveButton:) 
         userInfo:nil 
         repeats:YES]

You are using correct method to stop the timer i.e invalidate

You can also refer the link for more clarification.

Please let me know if you solve this problem through the above code.