[英]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.