我想以异步方式调用方法。这是一种从服务器获取HTML并将其设置为UIWebView
:
NSString *htmlTest = [BackendProxy getContent];
[webView loadHTMLString:htmlTest baseURL: nil];
[webView setUserInteractionEnabled:YES];
我想在数据提取期间在UIWebView
中启动活动指示器,因此我需要异步调用getContent
。我怎样才能做到这一点?
答案 0 :(得分:14)
这是Apple的新(ish)并发API GCD的一个很好的用例。
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^ {
// Background work here
NSLog(@"Finished work in background");
dispatch_async(dispatch_get_main_queue(), ^ {
NSLog(@"Back on main thread");
});
});
上的文档
答案 1 :(得分:8)
我建议performSelectorInBackground:withObject:
NSObject
。
如下所示:
- (void)loadIntoWebView: (id) dummy
{
NSString *html = [BackendProxy getContent];
[self performSelectorOnMainThread: @selector(loadingFinished:) withObject: html];
}
- (void)loadingFinished: (NSString*) html
{
// stop activity indicator
[webView loadHTMLString:html baseURL: nil];
[webView setUserInteractionEnabled:YES];
}
- (void) foo
{
// ...
// start activity indicator
[self performSelectorInBackground: @selector(loadIntoWebView:) withObject: nil];
}