Re: Cancelling dispatch_after?


Graham Cox
 

Makes sense, but there’s a bit of a problem.

To do that I’m going to have to create the block and keep a reference to it. That doesn’t seem to be how the GCD dispatch code snippet works - it just declares the block anonymously as part of the function call. OK, I get how to fix that. But the cancel would have to happen from a different method of the enclosing class, which means that the block reference is going to have to be an ivar (or property). That’s where it gets confusing because it’s unclear how to do that properly. Do I have to copy the block or retain it or what? When it’s just a local variable I don’t have to think about these issues.

In addition, the documentation for dispatch_after says that the function copies and releases the block on behalf of the caller. Wouldn’t that mean that my reference isn’t the same block, so the cancel wouldn’t work anyway?


—Graham

On 9 Nov 2017, at 9:13 am, Quincey Morris <quinceymorris@...> wrote:

On Nov 8, 2017, at 14:03 , Graham Cox <graham@...> wrote:

Is there a way to cancel a scheduled block used with dispatch_after(…)?
If you mean “cancel” in the sense of “prevent it from starting”, then the answer is yes, you can use “dispatch_block_cancel”:

https://developer.apple.com/documentation/dispatch/1431058-dispatch_block_cancel?language=objc

The original GCD didn’t have this ability, but it was added a few years ago.

You can’t cancel it once it’s started running, except by means of setting a flag as you mentioned earlier.

Join {cocoa@apple-dev.groups.io to automatically receive all group messages.