簡體   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