Dispatch_sync (dispatch_get_main_queue () UI oddity

This is for macOS not iOS.

If your executable code is in the GCD queue

dispatch_sync(dispatch_get_main_queue(), ^{
    //do UI stuff
});

      

is pretty much a way to make UI stuff on the main thread / queue, which seems to work well for iOS. MacOS seems to be a different story. Try this for a simple example

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // So my app is doing some background stuff
        // and I need a file from the user so

        // code blah blah code

        dispatch_sync(dispatch_get_main_queue(), ^{
            NSOpenPanel *op = [NSOpenPanel openPanel];

            [op runModal];
        });

        // resume code blah blah code
    });
}

      

when NSOpenPanel opens all kinds of weirdness. Scroll views are very erratic if at all, and directories are not displayed correctly. I'm just using NSOpenPanel here as an example, this also happens with any view that contains a scroll view (so I've tested already). This is mistake? Others see it or is it just me, and is there any other preferred way to do this?

+3


source to share


1 answer


The problem is that you are blocking the main thread as main_queue is a sequential dispatch queue. The main thread cannot run because it is blocked in the method runModal

.

After discussion here , the solution is to use beginWithCompletionHandler:

instead, which I checked to work:



//[op runModal];
[op beginWithCompletionHandler:^(NSInteger result) {
    NSLog(@"Done: %lu", (unsigned long)result);
}];

      

+3


source







All Articles