Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the background thread in Objective-C?

I am trying to run a while loop when I push the button, but I can not push the button because the while loop blocks the UI.

Is there a background thread where I can run the while loop and also push the UIButton?

like image 428
Martin Avatar asked Dec 09 '14 09:12

Martin


People also ask

How do I run a background thread?

To specify the thread on which to run the action, construct the Handler using a Looper for the thread. A Looper is an object that runs the message loop for an associated thread. Once you've created a Handler , you can then use the post(Runnable) method to run a block of code in the corresponding thread.

What is background thread in iOS?

Updated: 08/02/2020 by Computer Hope. In programming, a background thread is a thread that runs behind the scenes, while the foreground thread continues to run. For instance, a background thread may perform calculations on user input while the user is entering information using a foreground thread.

Why do you have to update the UI on the main thread?

It has been in the loop of constantly processing events and hibernation to ensure that user events can be responded as soon as possible. The reason why the screen can be refreshed is because `Main Runloop` is driving. Assume we use our Magical UIKit, and update UI on background threads.


2 Answers

Personally, I'd run a HUD activity indicator over the top of the UI and then run your loop in the background.

//Start the HUD here

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Run your loop here

    dispatch_async(dispatch_get_main_queue(), ^(void) {
         //stop your HUD here
         //This is run on the main thread


    });
});
like image 173
Compy Avatar answered Sep 24 '22 03:09

Compy


Try this

dispatch_async(dispatch_get_main_queue(), ^{
//  your code
});

Once it dispatches, you will not have full control over the operation. If you want to take the control of the operation. Use

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{

   // Background work
}];
like image 38
Dev Avatar answered Sep 23 '22 03:09

Dev