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
IOS: stop a NSTimer
提问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 NSTimer
in a variable and stop the timer using the invalidate
method. 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];