延长dispatch_after的调度时间

时间:2014-03-04 21:30:48

标签: ios nstimer

我在方法中有以下代码:

int64_t delayInSeconds = 2.0f;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);

dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
    // Do some stuff
}

如果在delayInSeconds之前调用该方法,我想将计时器再延长两秒钟。然后执行该块。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

然后我建议不要使用gcd。相反,你可以尝试:

  

[self performSelector:@selector(anyMethod)withObject:nil afterDelay:yourDelay]

     

//然后,如果您需要取消,请执行:

     

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(anyMethod)object:nil]

     

//只需在此处重新安排您的计时器。

答案 1 :(得分:1)

您可以使用NSTimer

- (void)someFunctionThatGetsCalledMoreThanOnce {
    ...

    [_myTimer invalidate];
    _myTimer = [NSTimer timerWithTimeInterval:2.0 
                                       target:self 
                                     selector:@selector(doStuff:) 
                                     userInfo:nil 
                                      repeats:NO];

    ...
}

- (void)doStuff:(NSTimer*)timer {
    // Do some stuff
}