[英]Updating UIProgressView within dispatch_async
我的應用程序使用dispatch_async進行了Google API調用,並獲取了我正在解析的JSON結果。 我想實現一個進度視圖,以便它根據我解析過的JSON響應的結果數量進行更新。
所以我的dispatch_async Google API調用是:
dispatch_async(myQueue, ^{
NSData* data1 = [NSData dataWithContentsOfURL:googleURL];
[self performSelectorOnMainThread:@selector(fetchResultsForGoogle:) withObject:data1 waitUntilDone:YES];
});
我的fetchResultsForGoogle: withObject:
方法解析結果,我想在屏幕上顯示進度視圖以及已處理結果的數量。 因此,在fetchResultsForGoogle...
方法中,我希望具有:
float percentage = (float)counter/(float)totalItems;
self.progressView.progress = percentage;
NSString *percentText = [NSString stringWithFormat:@"%f %% %@", percentage, @" complete"];
self.progressViewLabel.text = percentText;
但是我認為可以理解的是,當dispatch_async在另一個線程上執行時,如果不使用dispatch_async(dispatch_get_main_queue()
,就無法更新主線程上的視圖dispatch_async(dispatch_get_main_queue()
為了解決這個問題,我嘗試了兩種方法來實現(如下所示)但是這兩種方式對我都不起作用( progressView
和progressViewLabel
根本不會更新)。
計划A:
dispatch_async(myQueue, ^{
NSData* data1 = [NSData dataWithContentsOfURL:googleURL];
[self performSelectorOnMainThread:@selector(fetchResultsForGoogle:) withObject:data1 waitUntilDone:YES];
dispatch_async(dispatch_get_main_queue(), ^{
float percentage = (float)counter/(float)totalItems;
self.progressView.progress = percentage;
NSString *percentText = [NSString stringWithFormat:@"%f %% %@", percentage, @"complete"];
NSLog(@"Percentage: %@", percentText);
self.progressViewLabel.text = percentText;
});
});
方案B:
dispatch_async(myQueue, ^{
NSData* data1 = [NSData dataWithContentsOfURL:googleURL];
[self performSelectorOnMainThread:@selector(fetchResultsForGoogle:) withObject:data1 waitUntilDone:YES];
});
在fetchResultsForGoogle...
方法中:
dispatch_async(dispatch_get_main_queue(), ^{
float percentage = (float)counter/(float)totalItems;
self.progressView.progress = percentage;
NSString *percentText = [NSString stringWithFormat:@"%f %% %@", percentage, @"complete"];
NSLog(@"Percentage: %@", percentText);
self.progressViewLabel.text = percentText;
});
因此,非常感謝有關實現此方法的正確方法的任何想法或技巧!
編輯解決它,我修復了它。 在dispatch_async
塊中,我將其傳遞給performSelectorOnMainThread
。 因此,當我嘗試更新performSelectorOnMainThread
的進度視圖時,UI將不會更新,直到dispatch_async
完成。
因此,我將其更改為dispatch_async
塊內的performSelectorInBackgroundThread
,現在performSelectorOnMainThread
像應該那樣更新了UI。
我不熟悉這一切,但很高興我仍在學習新事物。
沒錯,您無法按照自己的方式更新主線程中的內容。 您必須在主線程上執行選擇器,如下所示:
我不確定您的百分比會在哪里變化,但是請在下面添加一行。 它將在主線程上更新標簽和progressView
[self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:percentage] waitUntilDone:NO];
-(void) updateProgress:(NSNumber *) num {
float percentage = [num floatValue];
self.progressView.progress = percentage;
NSString *percentText = [NSString stringWithFormat:@"%f %% %@", percentage, @" complete"];
self.progressViewLabel.text = percentText;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.