如何阻止NStimer活动?

47 iphone objective-c nstimer ios

可能重复:
NSTimer不会停止

在我的应用程序中,我使用NStimer每3秒调用一次动画函数.我想在计时器仍在运行时停止此计时器并调用另一个事件.这可能吗?

zap*_*aph 103

@interface
    NSTimer *autoTimer;

@implementation

// Start timer
    autoTimer = [NSTimer scheduledTimerWithTimeInterval:(3.0)
        target:self 
        selector:@selector(autoTimerFired:) 
        userInfo:nil 
        repeats:YES];

// Stop timer:
    [autoTimer invalidate];
    autoTimer = nil;
Run Code Online (Sandbox Code Playgroud)

  • 当然,在Swift中,`autoTimer.invalidate()`,并且不需要设置为`null`. (20认同)

con*_*are 43

首先,您要保留指向计时器的指针

self.packetTimer = [NSTimer timerWithTimeInterval:CONNECTION_TIMEOUT target:self selector:@selector(connectionTimeout:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:packetTimer forMode:NSDefaultRunLoopMode];
Run Code Online (Sandbox Code Playgroud)

如果您要在代码中的其他位置取消它,只需调用:

[self.packetTimer invalidate];
self.packetTimer = nil;
Run Code Online (Sandbox Code Playgroud)