How to update the interface in the task completion block?

In my application, I let the progress bar start the animation before sending an HTTP request. A completion handler is defined in a block. After receiving the response data, I hide the progress indicator from the inside of the block. My question is, as I know, UI updates should be done in the main thread. How can I be sure of this?

If I define a method in a window controller that updates the user interface, and let the block call the method instead of updating the interface directly, is that a solution?

+4
source share
2 answers

Alternatively, if your app targets iOS> = 4, you can use Grand Central Dispatch:

dispatch_async(dispatch_get_main_queue(), ^{ // This block will be executed asynchronously on the main thread. }); 

This is useful when your user logic cannot be easily expressed using separate selector and object arguments that accept the performSelect… methods.

To execute the block synchronously, use dispatch_sync() - but make sure that you are not currently executing in the main queue, or the GCD will block.

 __block NSInteger alertResult; // The __block modifier makes alertResult writable // from a referencing block. void (^ getResponse)() = ^{ NSAlert *alert = …; alertResult = [NSAlert runModal]; }; if ([NSThread isMainThread]) { // We're currently executing on the main thread. // We can execute the block directly. getResponse(); } else { dispatch_sync(dispatch_get_main_queue(), getResponse); } // Check the user response. if (alertResult == …) { … } 
+9
source

You probably misunderstood something. Using blocks does not mean that your code is running in the background thread. There are many plugins that work asynchronously (in another thread) and use blocks.

There are several solutions to your problem.

You can check if your code is running in the main thread using [NSThread isMainThread] . This will help you make sure that you are not in the background.

You can also perform actions in the main or background mode using performSelectorInMainThread:SEL or performSelectorInBackground:SEL .

The application crashes immediately when you try to call the user interface from the bakcground stream, so it’s pretty easy to find the error.

0
source

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


All Articles