ios 取消 dispatch_after() 方法?

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

cancel dispatch_after() method?

iosgrand-central-dispatch

提问by Oleg Shanyuk

Is there a way to cancel dispatch_after()scheduled for some time in future, and haven't fired so far? I'm trying to make something like a scheduler for updates from server, and this method is just like I want, but, I'd love to cancel and re-schedule it at some point. Is it possible at all or I have to fallback and use NSTimer?

有没有办法取消调度在未来一段时间内的dispatch_after()并且到目前为止还没有被解雇?我正在尝试为来自服务器的更新做一个调度程序之类的东西,这种方法就像我想要的那样,但是,我想在某个时候取消并重新安排它。是否有可能,或者我必须回退并使用 NSTimer?

回答by Florian Burel

There is NO way to prevent a dispatch_block from executing once it has been dispatch to it's queue, meaning that your dispatch_after cannot be canceled. Only option is to add in your block a condition to be checked at runtime to prevent execution. ie.

一旦 dispatch_block 被分派到它的队列,就没有办法阻止它执行,这意味着你的 dispatch_after 不能被取消。唯一的选择是在您的块中添加一个要在运行时检查的条件以防止执行。IE。

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^ {
if(self.shouldExecuteDispatchBlock)
{ // do your stuff }  });

回答by Oleg Shanyuk

OK, so, with all answers collected, and possible solutions, seems like the best one for this case (preserving simplicity) is calling performSelector:withObject:afterDelay:and cancelling it with cancelPreviousPerformRequestsWithTarget:call when desired. In my case - just before scheduling next delayed call:

好的,因此,收集了所有答案和可能的解决方案,对于这种情况(保持简单性),似乎最好的方法是在需要时performSelector:withObject:afterDelay:通过cancelPreviousPerformRequestsWithTarget:call调用和取消它。就我而言 - 就在安排下一次延迟通话之前:

[NSObject cancelPreviousPerformRequestsWithTarget: self selector:@selector(myDelayedMethod) object: self];

[self performSelector:@selector(myDelayedMethod) withObject: self afterDelay: desiredDelay];

回答by Zoltan Varadi

For this purpose i used this class:

为此,我使用了这个类:

https://github.com/SebastienThiebaud/dispatch_cancelable_block

https://github.com/SebastienThiebaud/dispatch_cancelable_block

you can call a cancel() function to revoke the execution of what's in the block.

您可以调用 cancel() 函数来撤销块中内容的执行。

回答by das

Use a dispatch timer source (that is what dispatch_afteruses internally anyway).

使用调度计时器源(dispatch_after无论如何都是内部使用的)。

A dispatch timer source can be canceled or its timer parameters changed after creation.

创建后可以取消调度计时器源或更改其计时器参数。