我让我的应用程序使用 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()
. 为了解决这个问题,我尝试了两种实现方法(如下所示),但这些方法中的任何一种都不适合我(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
在完成之前更新。
因此,我将其更改为块performSelectorInBackgroundThread
内部dispatch_async
,现在以performSelectorOnMainThread
应有的方式更新 UI。
我对这一切都很陌生,但我很高兴我仍在学习新事物。