简体   繁体   中英

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 ?

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


    });
});

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
}];

Way 1 :

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Write your code here 
});

Way 2 :

If you use performSelectorInBackground:withObject: to spawn a new thread.

Way 3 :

[NSThread detachNewThreadSelector:@selector(yourMethod:) toTarget:self withObject:nil];

There are many options for you, Grand Central Despatch is a good option, or you could use a NSTimer to trigger an event in the background every x milliseconds which may also work for you.

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

Or

NSTimer *refreshTimer;
refreshTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(YourMethodHere) userInfo:nil repeats:YES];

您可以使用dispatch_async来实现此目的。您必须在后台线程中运行循环,而UI更新必须在主线程中完成。这是一个链接

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM