ios 如何停止 NStimer 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1429571/
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 16:24:20  来源:igfitidea点击:

How to stop NStimer event?

iosobjective-ciphonenstimer

提问by zaph

Possible Duplicate:
NSTimer doesn't stop

可能重复:
NSTimer 不会停止

In my application I am using NStimer to call an animation function every 3 seconds. I want to stop this timer and called another event while the timer is still running. Is this possible?

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

回答by zaph

@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;

回答by coneybeare

First, you want to keep a pointer to the timer

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

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

If somewhere else in your code you want to cancel it, just call:

如果您想取消代码中的其他地方,只需调用:

[self.packetTimer invalidate];
self.packetTimer = nil;