Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two ways to get blocks dispatched to the main queue to run. The first is via <code>dispatch_main</code>, as mentioned by Drewsmits. However, as he also noted, there's a big problem with using <code>dispatch_main</code> in your test: <strong>it never returns</strong>. It will just sit there waiting to run any blocks that come its way for the rest of eternity. That's not so helpful for a unit test, as you can imagine.</p> <p>Luckily, there's another option. In the <code>COMPATIBILITY</code> section of the <a href="https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/dispatch_main.3.html" rel="nofollow"><code>dispatch_main</code> man page</a>, it says this:</p> <blockquote> <p>Cocoa applications need not call dispatch_main(). Blocks submitted to the main queue will be executed as part of the "common modes" of the application's main NSRunLoop or CFRunLoop.</p> </blockquote> <p>In other words, if you're in a Cocoa app, the dispatch queue is drained by the main thread's <code>NSRunLoop</code>. So all we need to do is keep the run loop running while we're waiting for the test to finish. It looks like this:</p> <pre><code>- (void)testDoSomething { __block BOOL hasCalledBack = NO; void (^completionBlock)(void) = ^(void){ NSLog(@"Completion Block!"); hasCalledBack = YES; }; [MyObject doSomethingAsyncThenRunCompletionBlockOnMainQueue:completionBlock]; // Repeatedly process events in the run loop until we see the callback run. // This code will wait for up to 10 seconds for something to come through // on the main queue before it times out. If your tests need longer than // that, bump up the time limit. Giving it a timeout like this means your // tests won't hang indefinitely. // -[NSRunLoop runMode:beforeDate:] always processes exactly one event or // returns after timing out. NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:10]; while (hasCalledBack == NO &amp;&amp; [loopUntil timeIntervalSinceNow] &gt; 0) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:loopUntil]; } if (!hasCalledBack) { STFail(@"I know this will fail, thanks"); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload