How to stop NSTimer at a specific point?

我的未来我决定 提交于 2019-12-11 07:24:58

问题


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.



来源:https://stackoverflow.com/questions/19608044/how-to-stop-nstimer-at-a-specific-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!