简体   繁体   English

如何在Objective-C中使用后台线程?

[英]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. 我按下按钮时尝试运行while循环,但我无法按下按钮,因为while循环阻止了UI。

Is there a background thread where I can run the while loop and also push the UIButton ? 是否有后台线程,我可以运行while循环并推送UIButton

Personally, I'd run a HUD activity indicator over the top of the UI and then run your loop in the background. 就个人而言,我会在UI的顶部运行一个HUD活动指示器,然后在后台运行你的循环。

//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 : 方式1:

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

Way 2 : 方式2:

If you use performSelectorInBackground:withObject: to spawn a new thread. 如果使用performSelectorInBackground:withObject:来生成新线程。

Way 3 : 方式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. 有很多选择,Grand Central Despatch是一个不错的选择,或者您可以使用NSTimer每隔x毫秒在后台触发一个事件,这也可能对您有用。

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更新必须在主线程中完成。这是一个链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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