我创建了一个简单的按钮游戏,每次点击按钮都会给用户一个点。该按钮每 1.5 秒随机出现在屏幕上。我希望游戏在 30 秒或 20 个随机按钮弹出窗口后结束。我一直在使用以下代码在屏幕上随机弹出按钮:
timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self
selector:@selector(moveButton:)
userInfo:nil
repeats:YES];
我已经在头文件中声明了计时器:
NSTimer *timer;
@property (nonatomic, retain) NSTimer *timer;
我已经阅读了关于使用计时器的Apple Docs,但未能完全理解它。我想也许我可以使用:
- (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
您还可以参考链接以获取更多说明。
如果您通过上面的代码解决此问题,请告诉我。