如何在特定点停止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
您也可以参考链接获取更多的说明。
请通过上面的代码告诉我你是否解决了这个问题。
- 无法接收来自Firebase 3.2.0主题的iOS推送通知
- Xcode App Submisson ERROR ITMS-90207:“无效的捆绑包
- 在iOS4的后台继续长时间运行的过程
- UICollectionViewFlowLayout子类在滚动和重新加载时崩溃访问数组
- 以编程方式向UIButton标签添加阴影
- UIScrollView +中心视图+ Ambigous Scrollable内容大小+许多iPhone大小
- 如何在单击TableViewCell中的button时增加标签和单元格大小。
- 如何在testing运行时在Xcode UItesting中模拟networking请求?
- 呈现模态视图控制器隐藏导航栏