繁体   English   中英

如何使用dispatch_async

[英]how to use dispatch_async

我用调度实现了一个线程,但是代码可以正常工作,但是进度UI无法正常工作

这是我的代码

@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

- (void)progressDeny {
    while (1) {
        if (progress >= 0 && progress <= 1.0) {
            NSLog(@"progress - 0.005!");
            progress -= 0.005;
            usleep(100000);
        }
    }
}

setProgress

- (void)setProgress {
    NSLog(@"%f", progress);
    [clickedProgress setProgress:progress animated:YES];
}

我看见了这个

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

为什么ui更新部分不起作用?

首先,您的progressDeny方法中的睡眠时间有点长,因此您可以使其更小。 其次,您的progressDeny方法中的while (1){}是一个无限循环,该方法永不返回,您可以尝试像这样更改它,例如:

- (void)progressDeny {
        if (progress >= 0 && progress <= 1.0) {
            NSLog(@"progress - 0.005!");
            progress -= 0.005;
            usleep(10);
        }
}

如果该代码的目的是显示进度视图并更新其值,则该代码将无法正常工作。 您至少犯了2个错误,才能使进度视图正常工作。

让我们看一下您的代码:

首先,您使用0.0初始化progress

progress = 0.0;

然后,在progressDeny内部,如果它equal 0并且没有提供任何退出循环的方法,则将其减去。 这将最终运行一次,然后陷入doing-nothing无限循环中。

- (void)progressDeny {
    while(1) {
        if (progress >= 0 && progress <= 1.0) {
            // Did you mean: progress += 0.005 ?
            progress -= 0.005;
            // ...
        }
    }
}

现在,让我们重构您的代码以使其工作:

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

或者您可以使用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.

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