我想异步调用一个方法。它是一种从服务器获取超文本标记语言并将其设置为UIWebView的方法
NSString *htmlTest = [BackendProxy getContent];
[webView loadHTMLString:htmlTest baseURL: nil];
[webView setUserInteractionEnabled:YES];我希望在数据获取期间在UIWebView中启动一个活动指示器,因此需要异步调用getContent。我怎样才能做到这一点呢?
发布于 2012-01-14 01:26:48
我推荐NSObject的performSelectorInBackground:withObject:。
如下所示:
- (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];
}发布于 2012-01-14 01:40:17
这是苹果新的(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");
});
});以下是有关dispatch queues的文档
https://stackoverflow.com/questions/8854100
复制相似问题