问题,我想加载一些HTML在一个UIWebView:如何强制主线程处理所有内容?有一个UIWebView
- (IBAction)buttonClicked:(id)sender {
[webView loadHTMLString:@"Hello World" baseURL:nil];
// a lot of other time-consuming code that has to perform in main thread
}
的问题是,该UIWebView的开始装车后“等费时的”代码完成。我想要的是,UIWebView直接开始加载。 UIWebView是否等待主线程并在主线程中的所有事件被处理后开始加载?
我可以强制主线程处理所有事情吗?
- (IBAction)buttonClicked:(id)sender {
[webView loadHTMLString:@"Hello World" baseURL:nil];
// !!! main thread, please PERFORM everything until here BEFORE going on !!!
// a lot of other time-consuming code that has to perform in main thread
}
PS:以下解决方法的工作原理,但我认为这不是最好的解决办法;-)
- (IBAction)buttonClicked:(id)sender {
[webView loadHTMLString:@"Hello World" baseURL:nil];
[NSThread detachNewThreadSelector:@selector(startNewThread) toTarget:self withObject:nil];
}
- (void)startNewThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread sleepForTimeInterval:1];
[self performSelectorOnMainThread:@selector(goBackToMainthread) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void)goBackToMainthread {
// a lot of other time-consuming code that has to perform in main thread
}
找到谢谢您的回答!在webViewDidFinishLoad中执行“其他耗时代码”的想法很好,但它可能有点复杂,因为我将“loadHTMLString”称为多个UIWebView的循环。我的整个代码中有很多UIWebViews,而且webViewDidFinishLoad被称为很多时间。如果应该调用“其他耗时的代码”,我会放置标志......强制主线程处理的可能性对我来说会更容易。 – Manni