ios 如何启动和停止 NSTimer?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12052914/
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
How Can I Start And Stop NSTimer?
提问by trojanfoe
I develop Stop Watch Application.
In my application, there are Two UIButtons , StartBtn
and StopBtn
, And also I use NSTimer
.
我开发秒表应用程序。在我的应用程序中,有两个 UIButtonsStartBtn
和StopBtn
,而且我使用NSTimer
.
Now, i want to start NSTimer
when user click on StartBtn
and also stop when your click on StopBtn
.
现在,我想NSTimer
在用户单击时开始,StartBtn
并在您单击时停止StopBtn
。
I know that NSTimer
is stopped by [MyTimerName invalidate];
method but I don't know how to start NSTimer
again?
我知道这NSTimer
被[MyTimerName invalidate];
方法阻止了,但我不知道如何重新开始NSTimer
?
回答by trojanfoe
The NSTimer
class is a bit awkward to use; rather than separating the creation/destruction from the start/stop, it's all rolled together. In other words the timer starts as soon as it's created and stops as soon as it's destroyed.
这个NSTimer
类使用起来有点尴尬;不是将创建/销毁与开始/停止分开,而是全部滚动在一起。换句话说,计时器在创建后立即启动,并在销毁后立即停止。
You therefore need to use the existenceof the NSTimer
object as a flag to indicate if it's running; something like this:
因此,您需要使用存在的的NSTimer
对象作为标志,以表明它是否运行; 像这样:
// Private Methods
@interface MyClass ()
{
NSTimer *_timer;
}
- (void)_timerFired:(NSTimer *)timer;
@end
@implementation MyClass
- (IBAction)startTimer:(id)sender {
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(_timerFired:)
userInfo:nil
repeats:YES];
}
}
- (IBAction)stopTimer:(id)sender {
if ([_timer isValid]) {
[_timer invalidate];
}
_timer = nil;
}
- (void)_timerFired:(NSTimer *)timer {
NSLog(@"ping");
}
回答by Freddy
You could always use fire to start a NStimer again
你总是可以用火重新启动一个 NStimer
[timer fire];
To stop it:
要停止它:
[timer invalidate];
//remember to set timer to nil after calling invalidate;
timer = nil;
回答by Suresh Varma
You can start the timer through
您可以通过以下方式启动计时器
#define kRefreshTimeInSeconds 1
NSTimer *myTimerName;
.
.
myTimerName = [NSTimer scheduledTimerWithTimeInterval: kRefreshTimeInSeconds
target:self
selector:@selector(handleTimer:)
userInfo:nil
repeats:YES];
Then the delegate function:
然后委托函数:
-(void)handleTimer: (id) sender
{
//Update Values in Label here
}
And to stop Timer
并停止计时器
-(void)stopTimer: (id) sender
{
if(myTimerName)
{
[myTimerName invalidate];
myTimerName = nil;
}
}