如何在特定点停止 NSTimer?

编程入门 行业动态 更新时间:2024-10-26 01:27:08
本文介绍了如何在特定点停止 NSTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了一个简单的按钮游戏,每次点击按钮都会为用户提供一个点.该按钮每 1.5 秒随机出现在屏幕上.我希望游戏在 30 秒或 20 个随机按钮弹出后结束.我一直在使用下面的代码让按钮在屏幕上随机弹出:

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;

但是它不能正常工作.我究竟做错了什么?我是 Objective-C 的新手,所以我不太熟悉它的工作原理.

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.

推荐答案

问题出在您的计时器方法上,您正在传递 moveButton 方法,但在下面的方法中,您正在停止计时器的方法名称不同,因此请尝试以下操作:-

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;}

更多推荐

如何在特定点停止 NSTimer?

本文发布于:2023-07-11 12:04:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093993.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在特定   NSTimer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!