在iOS中,我正在尝试在uiwebview中更新谷歌图表。我使用dispatch_async(dispatch_get_global ...)来解析json信息。在异步调用中,我使用dispatch_async(dispatch_get_main_queue ...)来执行主线程上的UI元素。我仍然在屏幕上发现一些延迟,但没有UI挂起。请帮助我以更好的方式编写下面的代码,这样一旦我从解析的信息中获得价值,我应该能够毫不拖延地生成图表。以下是代码:
dispatch_queue_t syncInAsync=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(syncInAsync, ^{
[self parse:url];
dispatch_async(dispatch_get_main_queue(), ^{
NSString* htmlString = [NSString stringWithFormat:@"<html><head><script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script><script type=\"text/javascript\">google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});google.setOnLoadCallback(drawChart);function drawChart() {var data = google.visualization.arrayToDataTable([['Reports', 'Value'],['Total', %@ ]]);var options = {title: 'Total Reports'};var chart = new google.visualization.PieChart(document.getElementById('piechart'));chart.draw(data, options);}</script></head><body><div id=\"piechart\" style=\" text-align: left width: 400px; height: 200px;\"></div></body></html>",number];
[_web1 loadHTMLString:htmlString baseURL:nil];
});
});
答案 0 :(得分:0)
使用sync
而不是异步线程更新UI。
试试这个 -
dispatch_queue_t syncInAsync=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(syncInAsync, ^{ [self parse:url]; dispatch_sync(dispatch_get_main_queue(), ^{ NSString* htmlString = [NSString stringWithFormat:@"<html><head><script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script><script type=\"text/javascript\">google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});google.setOnLoadCallback(drawChart);function drawChart() {var data = google.visualization.arrayToDataTable([['Reports', 'Value'],['Total', %@ ]]);var options = {title: 'Total Reports'};var chart = new google.visualization.PieChart(document.getElementById('piechart'));chart.draw(data, options);}</script></head><body><div id=\"piechart\" style=\" text-align: left width: 400px; height: 200px;\"></div></body></html>",number]; [_web1 loadHTMLString:htmlString baseURL:nil]; }); });
答案 1 :(得分:0)
在此块中写下您想要更改的内容
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//type here
}];
答案 2 :(得分:0)
你大多以正确的方式做这件事。我想做一些改变:
我想让parse方法执行代码在UI上呈现。所以,传递这样的完成块。在解析过程中显示加载叠加层总是一个好主意:
grep -B1 -A2 "Name: XXX"
这就是你的来电者的样子:
- (void)parse:(NSString *)iURL withCompletionBlock:MyCompletionBlock)iCompletionBlock {
// Parse JSON here. Show Loading Overlay.
// Once response is available
dispatch_async(dispatch_get_main_queue(), ^{
// Remove Loading Overlay.
// Execute completion block
completionBlock();
});
}