NSTimer 有时会在时间之前被解雇

NSTimer is sometimes getting fired before time

我正在设置一个计时器,如果不满足特定条件,则在 30 秒后触发一个方法 else/otherwise 计时器将失效。 这就是我在做什么 我正在创建这样的计时器 属性

@property (nonatomic) NSTimer *timer;

现在我正在以某种方式启动我的计时器

- (void) createAPIXML
{
    if (_isGenerateRootTag) {
        _root = (DDXMLElement *) [DDXMLNode elementWithName:[[MainViewController sharedViewController] rootElement]];
    _isGenerateRootTag = FALSE;
}
    dispatch_async(dispatch_get_main_queue(), ^{
    _timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFireMethod) userInfo:nil repeats:NO];
    NSLog(@"**************************STARTING THE TIMER %@**********************",_timer.description);
});
[self sendRequest];
}

现在,我继续进行进一步的验证,如果满足所有条件,我会通过其他一些方法使我的计时器无效

NSLog(@"**************************KILLING TIMER %@ FROM VALIDATE RESPONSE METHOD**********************",_timer.description);
        // Invalidate timer..
        if (_timer != nil) {
            [_timer invalidate];
            _timer = nil;
        }

如果不满足条件并且超过了 30 秒,我的 timerFireMethod 将被调用

- (void)timerFireMethod
{
NSLog(@"Timer Methods Metho gor called with timer Instance %@",_timer.description);
}

这是一个间歇性问题,对我来说看起来像是竞争条件,但确实会发生并导致很多问题.. 我在这里做错了什么需要你的专家建议..我被卡住了

看来您必须在重新分配源之前使计时器无效: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/

Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated.

所以,做一些类似的事情

dispatch_async(dispatch_get_main_queue(), ^{
    if (timer) { 
         [_timer invalidate];
         _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFireMethod) userInfo:nil repeats:NO];

即重新设置计时器并不会使旧计时器失效,还要确保

you should always call the invalidate method from the same thread on which the timer was installed.