How do you schedule a block to run on the next run loop iteration?

后端 未结 5 2269
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 04:36

I want to be able to execute a block on the next run loop iteration. It\'s not so important whether it gets executed at the beginning or the end of the next run

相关标签:
5条回答
  • 2020-12-02 05:06

    Rob answer is great and informative. I'm not trying to replace it.

    Just reading the UIView documentation, I found :

    completion

    A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL.

    So an easy solution would be:

    UIView.animate(withDuration: 0) {
        // anything
    }
    
    0 讨论(0)
  • 2020-12-02 05:09

    I do not believe there is any API that will allow you to guarantee code gets run on the very next event loop turn. I'm also curious why you need a guarantee that nothing else has run on the loop, the main one in particular.

    I can also confirm that using the perforSelector:withObject:afterDelay does use a runloop-based timer, and will have functionally similar behavior to dispatch_async'ing on dispatch_get_main_queue().

    edit:

    Actually, after re-reading your question, it sounds like you only need the current runloop turn to complete. If that is true, then dispatch_async is exactly what you need. In fact, all of the code above does make the guarantee that the current runloop turn will complete.

    0 讨论(0)
  • 2020-12-02 05:17

    You might not be aware of everything that the run loop does in each iteration. (I wasn't before I researched this answer!) As it happens, CFRunLoop is part of the open-source CoreFoundation package, so we can take a look at exactly what it entails. The run loop looks roughly like this:

    while (true) {
        Call kCFRunLoopBeforeTimers observer callbacks;
        Call kCFRunLoopBeforeSources observer callbacks;
        Perform blocks queued by CFRunLoopPerformBlock;
        Call the callback of each version 0 CFRunLoopSource that has been signalled;
        if (any version 0 source callbacks were called) {
            Perform blocks newly queued by CFRunLoopPerformBlock;
        }
        if (I didn't drain the main queue on the last iteration
            AND the main queue has any blocks waiting)
        {
            while (main queue has blocks) {
                perform the next block on the main queue
            }
        } else {
            Call kCFRunLoopBeforeWaiting observer callbacks;
            Wait for a CFRunLoopSource to be signalled
              OR for a timer to fire
              OR for a block to be added to the main queue;
            Call kCFRunLoopAfterWaiting observer callbacks;
            if (the event was a timer) {
                call CFRunLoopTimer callbacks for timers that should have fired by now
            } else if (event was a block arriving on the main queue) {
                while (main queue has blocks) {
                    perform the next block on the main queue
                }
            } else {
                look up the version 1 CFRunLoopSource for the event
                if (I found a version 1 source) {
                    call the source's callback
                }
            }
        }
        Perform blocks queued by CFRunLoopPerformBlock;
    }
    

    You can see that there are a variety of ways to hook into the run loop. You can create a CFRunLoopObserver to be called for any of the “activities” you want. You can create a version 0 CFRunLoopSource and signal it immediately. You can create a connected pair of CFMessagePorts, wrap one in a version 1 CFRunLoopSource, and send it a message. You can create a CFRunLoopTimer. You can queue blocks using either dispatch_get_main_queue or CFRunLoopPerformBlock.

    You will need to decide which of these APIs to use based on when you are scheduling the block, and when you need it to be called.

    For example, touches are handled in a version 1 source, but if you handle the touch by updating the screen, that update isn't actually performed until the Core Animation transaction is committed, which happens in a kCFRunLoopBeforeWaiting observer.

    Now suppose you want to schedule the block while you're handling the touch, but you want it to be executed after the transaction is committed.

    You can add your own CFRunLoopObserver for the kCFRunLoopBeforeWaiting activity, but this observer might run before or after Core Animation's observer, depending on the order you specify and the order Core Animation specifies. (Core Animation currently specifies an order of 2000000, but that is not documented so it could change.)

    To make sure your block runs after Core Animation's observer, even if your observer runs before Core Animation's observer, don't call the block directly in your observer's callback. Instead, use dispatch_async at that point to add the block to the main queue. Putting the block on the main queue will force the run loop to wake up from its “wait” immediately. It will run any kCFRunLoopAfterWaiting observers, and then it will drain the main queue, at which time it will run your block.

    0 讨论(0)
  • 2020-12-02 05:20

    I wrote myself an NSObject category which accepts a variable delay value, based on another stackoverflow question. By passing a value of zero you are effectively making the code run on the next available runloop iteration.

    0 讨论(0)
  • 2020-12-02 05:24

    dispatch_async on mainQueue is a good suggestion but it does not run on the next run loop it is inserted into the current run in the loop.

    To get the behavior you are after you will need to resort to the traditional way:

    [self performSelector:@selector(myMethod) withObject:nil afterDelay:0];
    

    This also gives the added advantage is it can be canceled using NSObject's cancelPreviousPerforms.

    0 讨论(0)
提交回复
热议问题