IOS:停止一个 NSTimer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8524290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:53:59  来源:igfitidea点击:

IOS: stop a NSTimer

iosxcodenstimer

提问by cyclingIsBetter

Possible Duplicate:
NSTimer doesn't stop

可能重复:
NSTimer 不会停止

I have this code:

我有这个代码:

[NSTimer scheduledTimerWithTimeInterval:110.0
                                 target:self
                               selector:@selector(targetMethod:)
                               userInfo:nil
                                repeats:YES];

- (void) targetMethod:(NSTimer) timer{
NSLog(@"Hello World");}

in targetMethod I can stop timer with [timer invalidate], but out of this method, How can I stop targetMethod?

在 targetMethod 中,我可以使用 [timer invalidate] 停止计时器,但是在此方法之外,我如何停止 targetMethod?

回答by Raphael Petegrosso

You can keep your NSTimerin a variable and stop the timer using the invalidatemethod. Like the following:

您可以将NSTimer变量保留在变量中并使用该invalidate方法停止计时器。像下面这样:

NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:110.0
                                 target:self
                               selector:@selector(targetMethod:)
                               userInfo:nil
                                repeats:YES];

[myTimer invalidate];

回答by user523234

One way to do it is to create NSTimer *timer; as a global variable so you can have a handle to the timer. Some thing likes this:

一种方法是创建 NSTimer *timer; 作为全局变量,因此您可以拥有计时器的句柄。有些事情是这样的:

NSTimer *timer;  //global var

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

To stop timer somewhere in the same class:

要在同一班级的某处停止计时器:

[timer invalidate];