[英]how to use dispatch_async
I implemented a thread with dispatch, but the code works fine, but the progress UI does not work 我用调度实现了一个线程,但是代码可以正常工作,但是进度UI无法正常工作
This is my code 这是我的代码
@interface thirdController () {
float progress;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
progress = 0.0;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self progressDeny];
dispatch_async(dispatch_get_main_queue(), ^{
[self setProgress];
});
});
}
progressDeny progressDeny
- (void)progressDeny {
while (1) {
if (progress >= 0 && progress <= 1.0) {
NSLog(@"progress - 0.005!");
progress -= 0.005;
usleep(100000);
}
}
}
setProgress setProgress
- (void)setProgress {
NSLog(@"%f", progress);
[clickedProgress setProgress:progress animated:YES];
}
I saw this 我看见了这个
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
Why is the ui update part not working? 为什么ui更新部分不起作用?
First, the sleep time in your progressDeny
method is a bit long, so you can make it smaller. 首先,您的progressDeny
方法中的睡眠时间有点长,因此您可以使其更小。 Second, the while (1){}
in your progressDeny
method is a endless loop and the method never returns, you can try to change it like this, for example: 其次,您的progressDeny
方法中的while (1){}
是一个无限循环,该方法永不返回,您可以尝试像这样更改它,例如:
- (void)progressDeny {
if (progress >= 0 && progress <= 1.0) {
NSLog(@"progress - 0.005!");
progress -= 0.005;
usleep(10);
}
}
The code is not working fine if the purpose of it is present progress view & update its value. 如果该代码的目的是显示进度视图并更新其值,则该代码将无法正常工作。 You made at least 2 bugs to make progress view work. 您至少犯了2个错误,才能使进度视图正常工作。
Let take a look into your code: 让我们看一下您的代码:
First, you init progress
with 0.0
首先,您使用0.0
初始化progress
progress = 0.0;
Then, inside progressDeny
, you subtracted it if it is equal
to 0
& did not provide any way to exit the loop. 然后,在progressDeny
内部,如果它equal
0
并且没有提供任何退出循环的方法,则将其减去。 This will ended up being run once then stuck in doing-nothing
infinite loop. 这将最终运行一次,然后陷入doing-nothing
无限循环中。
- (void)progressDeny {
while(1) {
if (progress >= 0 && progress <= 1.0) {
// Did you mean: progress += 0.005 ?
progress -= 0.005;
// ...
}
}
}
Now, let refactor your code to make it work: 现在,让我们重构您的代码以使其工作:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (progress <= 1.0) {
progress += 0.005;
dispatch_async(dispatch_get_main_queue(), ^{
[clickedProgress setProgress:progress];
});
usleep(100000);
}
});
Or you can make it with NSTimer
instead of GCD
: 或者您可以使用NSTimer
而不是GCD
:
[NSTimer scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
if (progress <= 1.0) {
progress += 0.005;
[clickedProgress setProgress:progress];
} else {
[timer invalidate];
timer = nil;
}
}];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.