Running Cocoa GUI on a non-core topic

I am having a problem with gui / threading when developing a cocoa user interface. The application is designed as follows:

Main thread (# 1): parses arguments, loads plugins, etc.

Gui thread (#?): Launches gui, processes events, etc. His stream is gui.

The cocoa structure is unsafe, but provides one rule, the GUI should work in the main thread. For verification, a statement is used. To try to get around this, I implemented the launch method itself (code below) - http://cocoawithlove.com/2009/01/demystifying-nsapplication-by.html - manual. But I'm missing something. The window opens, but remains empty (completely white). Although, if I make a call in the main thread, it works fine.

So basically I need to find out what is missing.

- (void)run { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self finishLaunching]; shouldKeepRunning = YES; do { [pool release]; pool = [[NSAutoreleasePool alloc] init]; NSEvent *event = [self nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES]; [self sendEvent:event]; [self updateWindows]; } while (shouldKeepRunning); [pool release]; } - (void)terminate:(id)sender { shouldKeepRunning = NO; } 
+6
source share
3 answers

not to do. This approach will never work. Even if you fix your current problem (the window is not drawing), you will immediately encounter another incomprehensible, impossible to fix problem, another, and another. Cocoa expects the GUI thread to be the main thread, ending the story.

+14
source

Why not reverse the problem? Ask the main thread to create a thread (let me call it the application thread) and then block it until an irregular graphical interface appears. The application stream will analyze the arguments, load plugins, etc. After initialization is complete, the application thread will signal to the main thread to start and run the graphical interface.

+1
source

Do everything in the background thread except updating the GUI. I see that you only have a line where you need to update the GUI. So do it the way you do it, except that you do all GUI updates in the main thread:

 dispatch_async(dispatch_get_main_queue(), ^ { [self updateWindows]; }); 

Now I do not know what updateWindows is, I assumed that this will not create race conditions.

+1
source

Source: https://habr.com/ru/post/911043/


All Articles