如何在特定点停止NSTimer?

我创build了一个简单的button游戏,每按一下button就可以给用户一个点。 该button每1.5秒随机出现在屏幕上。 我希望游戏在30秒后或20个随机popupbutton后结束。 我一直在使用下面的代码在屏幕上随意popupbutton:

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

我已经在头文件中声明了计时器:

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

我已阅读使用计时器的 Apple文档,但未能完全理解它。 我想也许我可以使用:

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

但它不能正常工作。 我究竟做错了什么? 我是新来的Objective-C,所以我不熟悉如何工作。

问题是你的计时器方法你传递moveButton方法,但在下面的方法停止计时器,方法名称是不同的所以试试这个: –

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

//只是改变下面的方法名称

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

如果你正在使用新版本的Xcode,那么你不需要声明

 NSTimer *timer; 

并在计划一个计时器时,您可以使用

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

代替

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

你正在使用正确的方法来停止计时器,即invalidate

您也可以参考链接获取更多的说明。

请通过上面的代码告诉我你是否解决了这个问题。